如何检测 0 长度 UDP 数据报的接收
我正在考虑编写/实现一个基于 UDP 的协议,该协议将使用零长度数据报作为“hello”消息。虽然我预计发送零长度数据报不会出现问题,但我不确定是否可以收到。
recvfrom 返回读取的字节数,但保留 0 以用于有序关闭。
read 返回读取的字节数,但 0 保留给 EOF。
选择“将监视字符是否可供读取”。
如何检测零长度数据报的接收?
I was considering writing/implementing a UDP-based protocol that would use a zero-length datagram as a 'hello' message. And while I don't expect to have a problem sending a zero-length datagram, I'm not certain I can receive one.
recvfrom returns the number of bytes read, but 0 is reserved for an orderly shutdown.
read returns number of bytes read, but 0 is reserved for EOF.
select "will be watched to see if characters become available for reading".
How would one detect the receipt of a zero-length datagram?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 TCP 套接字上调用
recvfrom
时,如果已收到 FIN 数据包(有序关闭),您将收到零字节读取。 UDP 没有有序关闭的概念,并且没有数据从发送方传输到接收方来指示套接字正在关闭。该协议是完全无状态的,并且接收到的每个数据报都独立于接收者的观点。因此,我不知道任何场景中,UDP 套接字上的 recvfrom 的零字节返回代码是由接收到的零长度数据报以外的任何内容引起的。When calling
recvfrom
on a TCP Socket, you will receive a zero byte read if a FIN packet has been received (an orderly shutdown). UDP has no concept of orderly shutdowns, and no data is transmitted from the sender to receiver to indicate a socket being closed. The protocol is completely stateless and every datagram received is independent from the receiver's point of view. As such, I am not aware of any scenerios in which a zero byte return code from recvfrom on a UDP socket would be caused by anything other than a zero length datagram being received.对于 udp,当接收到有效负载长度为 0 的 udp 数据包时,对
recvfrom
的正常调用将返回 0(请参阅 在 Linux 下,recv 能否在 UDP 上返回 0?)。您可以通过执行简单的 sendto/recvfrom 测试来测试这一点:
您引用的文档来自 recvfrom 的手册页:“返回读取的字节数,但保留 0 以用于有序关闭”。该声明仅适用于 TCP。
For udp, a normal call to
recvfrom
will return 0 when receiving a udp packet with 0 length payload (see Under Linux, can recv ever return 0 on UDP?).You can test this by doing a simple sendto/recvfrom test:
The documentation you are quoting is from the man page for recvfrom: "returns the number of bytes read, but 0 is reserved for an orderly shutdown". That statement applies only to TCP.