UDP client does not receive data without bind()

Sorcrer picture Sorcrer · Jan 27, 2015 · Viewed 7.8k times · Source

I refereed to the UDP client program from binarytides and I was able to send a UDP packet frompy PC to the UDP server which is My embedded device and this device echoes back a UDP message.

In this PC-UDP client code it is expected to get the echoed message ,but I'm not getting any echoes back.So I ran a UDP server in my PC which listens for the incoming data and prints it , I was able to see the echoed message from my Embedded device.

When I added these lines just before the while(1) loop in the code,and now I'm able to see the Echoed back message.

 //setup address structure
memset((char *) &si_server, 0, sizeof(si_server));
si_server.sin_family = AF_INET;
si_server.sin_port = htons(PORT);
si_server.sin_addr.S_un.S_addr = INADDR_ANY;

if( bind(s ,(struct sockaddr *)&si_server , sizeof(si_server)) == SOCKET_ERROR)
{
    printf("Bind failed with error code : %d" , WSAGetLastError());
    exit(EXIT_FAILURE);
}
puts("Bind done");

Any thoughts on what might be causing the issue?

Answer

Sorcrer picture Sorcrer · Jan 30, 2015

Hi Finally I found the answer from EJP answer

It is only necessary to bind() a server, because the clients need a fixed port number to send to. A client needn't bind() at all: an automatic bind() will take place on the first send()/sendto()/recv()/recvfrom() using a system-assigned local port number.

With the help of wireshark I was able to see My PC was sending data from Port 53701 and on first sendto() this port got automatically bind'ed , so had to do a explicit binding.