C++ problem with Datagram (UDP)winsocket to sendto and recvfrom on the same socket through the loopback adapter
I am trying to send some data with a udp socket and receive them back on the same socket through windows loopback adatper. In my network properties I set the loopback adapter to have the following ip 192.168.1.1
the recvfrom function returns -1 indicating an error. I also monitor the traffic on the loopback adapter with wireshark and nothing seem to be sent to the loopback adapter, I see no trafic.
Is it true that on windows we can't use the loopback address(127.0.0.1) ? I saw that on some forums, that is why I try to use the loopback adapter. I also tried to send directly to my own ip, but it gives no better results. Btw it is possible to send to his own ip and get the data back?
I would appreciate any help and just in case, I am new to socket programming.
Below is my code:
#define DST "192.168.1.1"
int _tmain(int argc, char* argv[])
{
int numbytes;
int bytes_sent;
int server_sock;
char send_msg[100];
int send_msg_length = 100;
char rcv_msg[100] = { 0 };
int rcv_msg_length = 100;
int i;
开发者_如何学C
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
return 1;
}
sockaddr_in to_addr;
sockaddr_in me;
unsigned short Port = 27015;
to_addr.sin_family = AF_INET;
to_addr.sin_port = htons(Port);
to_addr.sin_addr.s_addr = inet_addr(DST);
me.sin_family = AF_INET;
me.sin_port = 0;
me.sin_addr.s_addr = htonl(INADDR_ANY);
memset( &(me.sin_zero), '\0', 8 );
if ((server_sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("talker: socket");
}
if ( bind( server_sock, (SOCKADDR *)&me, sizeof( me ) ) == -1)
{
printf("Error binding/n");
return 1;
};
int length = sizeof( to_addr );
bytes_sent = sendto(server_sock, send_msg, send_msg_length, 0, (SOCKADDR *)&to_addr, length);
if (bytes_sent == -1)
{
perror("talker: sendto");
exit(1);
}
printf("Sent %d bytes to %s\n", bytes_sent, DST);
printf("listener: waiting to recvfrom...\n");
if ( numbytes = recvfrom(server_sock, rcv_msg, rcv_msg_length, 0, (SOCKADDR *)&to_addr, &length ) )
{
perror("recvfrom");
exit(1);
}
closesocket(server_sock);
WSACleanup();
return 0;
}
You are binding your server socket to port 0
, i.e. asking the OS to assign random port number to it. That has to be the same port you are sending to, 27015
in your case.
Also, you don't have to byte-swap INADDR_ANY
.
精彩评论