在 Linux 下,recv 可以在 UDP 上返回 0 吗? [英] Under Linux, can recv ever return 0 on UDP?
问题描述
我只是在清理我们不久前编写的一些代码,并注意到对于 udp 套接字,0 被视为连接关闭.
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.
我很确定这是从等效的 tcp 版本移植相同的 recv 循环的结果.但这让我想知道.recv 可以为 udp 返回 0 吗?在 tcp 上,它表示另一端已关闭连接.udp没有连接的概念所以能返回0吗?如果可以,它的含义是什么?
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?
注意:Linux 中的手册页不区分 udp 和 tcp,返回代码为零,这可能是我们在代码中保留检查的原因.
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.
推荐答案
udp没有连接的概念所以能返回0吗?和如果可以,是什么意思
udp doesn't have the concept of a connection so can it return 0? and if it can, what is it's meaning
表示收到了一个长度为 0 的数据报.来自伟大的 UNP:
It means a 0-length datagram was received. From the great UNP:
可以接受长度为 0 的数据报.在 UDP 的情况下,这导致包含 IP 报头的 IP 数据报(通常为 20 个字节)IPv4 和 IPv6 的 40 个字节),一个 8 字节的 UDP 标头,并且没有数据.这也意味着 recvfrom 的返回值 0 是可以接受的对于一个数据报协议:这并不意味着对端已经关闭了连接,就像从 TCP 套接字上读取的返回值 0 一样.由于 UDP 是无连接的,所以没有关闭 UDP 这样的事情连接.
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.
这篇关于在 Linux 下,recv 可以在 UDP 上返回 0 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!