简体   繁体   中英

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. 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?

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.

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:

    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". That statement applies only to TCP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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