Skip to content
Advertisement

Under Linux, can recv ever return 0 on UDP?

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 result of porting the same recv loop from the equivalent tcp version. But it makes me wonder. Can recv return 0 for udp? on tcp it signals the other end has closed the connection. udp doesn’t have the concept of a connection so can it return 0? and if it can, what is it’s meaning?

Note: the man page in linux does not distinguish udp and tcp for a return code of zero which may be why we kept the check in the code.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement