Under Linux, can recv ever return 0 on UDP?

前端 未结 2 587
余生分开走
余生分开走 2021-01-11 09:31

I\'m just cleaning up some code we wrote a while back and noticed that for a udp socket, 0 is being treated as the connection closed.

I\'m quite sure this was the re

相关标签:
2条回答
  • 2021-01-11 10:01

    In Linux there are two reasons that recvfrom on a UDP socket could return zero:

    1) a zero-length datagram was received, or 2) shutdown was called on the socket

    The second behavior is useful because it allows you to unblock a thread that is waiting on the socket. However, there is no way for the caller of recvfrom to know whether the socket was shut down or whether a zero-length datagram was received. For this you need some other way to signal to the thread that the socket was shut down, for example using a shared variable.

    The second behavior also seems to contradict the recv(2) man page, which says this:

    When  a  stream socket peer has performed an orderly shutdown, the return 
    value will be 0 (the traditional "end-of-file" return).
    

    Clearly, it also occurs for UDP sockets, which are not stream sockets.

    0 讨论(0)
  • 2021-01-11 10:20

    udp doesn't have the concept of a connection so can it return 0? and if it can, what is it's meaning

    It means a 0-length datagram was received. From the great UNP:

    Writing a datagram of length 0 is acceptable. In the case of UDP, this results in an IP datagram containing an IP header (normally 20 bytes for IPv4 and 40 bytes for IPv6), an 8-byte UDP header, and no data. This also means that a return value of 0 from recvfrom is acceptable for a datagram protocol: It does not mean that the peer has closed the connection, as does a return value of 0 from read on a TCP socket. Since UDP is connectionless, there is no such thing as closing a UDP connection.

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