| mptlptr 2005-11-29, 3:45 pm |
| Say I have 2 servers (named A and B) and 1 client. Server A has Server B's address information stored in "struct sockaddr_in servb_addr". I want server A to send server B's address information to the client (since the client cannot directly communicate with server B) and the client should store this address information in " struct sockaddr_in server_addr". How would I do this?
Mainly what I'm not sure of is how to convert "servb_addr.sin_addr.s_addr" and "servb_addr.sin_port" to a form suitable for transmission and then once I receive it how would I convert it back and store it in "server_addr"?
I have an excerpt of my code below (please assume that "udp_sockfd" is set up correctly, and that "cli_addr" contains the correct address information of the client). It seems, however, that the IP address and port number are not being sent/received correctly. Can you guys give me some tips?
Thanks a lot
Server A code:
char *servbip; //send IP address of server B
servbip = inet_ntoa(servb_addr.sin_addr);
x = sendto(udp_sockfd, servbip, sizeof(servbip), 0, (struct sockaddr *) &cli_addr, sizeof(cli_addr));
char servbportbuffer[4];
int servbport = ntohs(servb_addr.sin_port); //send port number of chat server
sprintf(servbportbuffer, "%d", chatport);
x = sendto(udp_sockfd, &servbportbuffer, sizeof(servbportbuffer), 0, (struct sockaddr *) &cli_addr, sizeof(cli_addr));
Client Code:
char ip[4];
int fromlen = sizeof(temp_addr);
x = recvfrom(udp_sockfd, ip, sizeof(ip), 0, (struct sockaddr *) &temp_addr, &fromlen);
inet_aton(ip, &server_addr.sin_addr);
char portbuffer[4];
x = recvfrom(udp_sockfd, portbuffer, sizeof(portbuffer), 0, (struct sockaddr *) &temp_addr, &fromlen);
int port = atoi(portbuffer);
server_addr.sin_port = htons(port); |