简体   繁体   English

如何检测0长度UDP数据报的接收

[英]How to detect receipt of a 0-length UDP datagram

I was considering writing/implementing a UDP-based protocol that would use a zero-length datagram as a 'hello' message. 我正在考虑编写/实现一个基于UDP的协议,该协议将使用零长度数据报作为“hello”消息。 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. recvfrom返回读取的字节数,但0保留用于有序关闭。

read returns number of bytes read, but 0 is reserved for EOF. read返回读取的字节数,但为EOF保留0。

select "will be watched to see if characters become available for reading". 选择 “将观看人物是否可以阅读”。

How would one detect the receipt of a zero-length datagram? 如何检测零长度数据报的接收?

When calling recvfrom on a TCP Socket, you will receive a zero byte read if a FIN packet has been received (an orderly shutdown). 在TCP套接字上调用recvfrom时,如果收到FIN数据包(有序关闭),您将收到零字节读取。 UDP has no concept of orderly shutdowns, and no data is transmitted from the sender to receiver to indicate a socket being closed. UDP没有有序关闭的概念,也没有数据从发送方传输到接收方以指示套接字被关闭。 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套接字上的recvfrom的零字节返回码将由除了接收零长度数据报之外的任何东西引起。

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? ). 对于udp,当接收到具有0长度有效负载的udp数据包时,对recvfrom的正常调用将返回0(请参阅在Linux下,可以在UDP上返回0? )。

You can test this by doing a simple sendto/recvfrom test: 您可以通过执行简单的sendto / recvfrom测试来测试:

    const int howManyBytesToSend = 0;
    if(sendto(sock, buf, howManyBytesToSend, 0, (struct sockaddr*) &addr, addrlen) < 0)
    {
        return EXIT_FAILURE;
    }

    if((recv_len = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *) &addr, (socklen_t*)&addrlen)) < 0)
    {
        return EXIT_FAILURE;
    }

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". 您引用的文档来自recvfrom的手册页:“返回读取的字节数,但为有序关闭保留0”。 That statement applies only to TCP. 该声明仅适用于TCP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM