Do I have to bind a UDP socket in my client program to receive data? (I always get WSAEINVAL)

前端 未结 4 1503
挽巷
挽巷 2020-12-02 18:27

I am creating a UDP socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP) via Winsock and trying to recvfrom on this socket, but it a

相关标签:
4条回答
  • 2020-12-02 19:13

    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.

    0 讨论(0)
  • 2020-12-02 19:14

    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.

    0 讨论(0)
  • 2020-12-02 19:19

    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.

    0 讨论(0)
  • 2020-12-02 19:19

    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.

    0 讨论(0)
提交回复
热议问题