I am creating a UDP socket (AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
) via Winsock and trying to recvfrom
on this socket, but it a
Your other code sample works because you are using sendto
before recvfrom
. If a UDP socket is unbound and either sendto
or connect
are called on it, the system will automatically bind it for you and thus the recvfrom
call later on will succeed. recvfrom
will not bind a socket, as this call expects the socket to have been bound already, or an error will be thrown.
I had the same problem a few weeks ago, the following remarks helped me to understand whether an explicit bind() call is necessary:
recvfrom function (MSDN)
Explicit binding is discouraged for client applications. For client applications using this function, the socket can become bound implicitly to a local address through sendto, WSASendTo, or WSAJoinLeaf.
sendto function (MSDN)
Note If a socket is opened, a setsockopt call is made, and then a sendto call is made, Windows Sockets performs an implicit bind function call. If the socket is unbound, unique values are assigned to the local association by the system, and the socket is then marked as bound.
With UDP, you have to bind()
the socket in the client because UDP is connectionless, so there is no other way for the stack to know which program to deliver datagrams to for a particular port.
If you could recvfrom()
without bind()
, you'd essentially be asking the stack to give your program all UDP datagrams sent to that computer. Since the stack delivers datagrams to only one program, this would break DNS, Windows' Network Neighborhood, network time sync....
You may have read somewhere on the net that binding in a client is lame, but that advice only applies to TCP connections.
Here it says the following:
Parameters
s [in]: A descriptor identifying a bound socket.
...
Return Value
WSAEINVAL: The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled, or (for byte stream-style sockets only) len was zero or negative.
As far as I remember bind is not required for a UDP socket because a bind call is made for you by the stack. I guess it's a Windows thing to require a bind on a socket used in a recvfrom call.