NK-cell
NK-cell

Reputation: 1195

What is the reason for using UNIX sockets "zero-length datagrams"?

In recv()'s man page I found that return value can be zero in such case:

Datagram sockets in various domains (e.g., the UNIX and Internet domains) permit zero-length datagrams. When such a datagram is received, the return value is 0.

When or why should one use zero-length datagrams in UNIX socket intercommunication? What's its purpose?

Upvotes: 4

Views: 343

Answers (2)

Shawn
Shawn

Reputation: 52549

One example I stumbled upon yesterday while researching the answer to another question.

In the old RFC 868 protocol for getting the current time of a remote server, the workflow for using UDP looks like:

When used via UDP the time service works as follows:

   S: Listen on port 37 (45 octal).

   U: Send an empty datagram to port 37.

   S: Receive the empty datagram.

   S: Send a datagram containing the time as a 32 bit binary number.

   U: Receive the time datagram.

   The server listens for a datagram on port 37.  When a datagram
   arrives, the server returns a datagram containing the 32-bit time
   value.  If the server is unable to determine the time at its site, it
   should discard the arriving datagram and make no reply.

In this case, the server has to receive a datagram to be alerted that a user is requesting the time (And to know what address to send a reply to), due to UDP's connectionless nature (The TCP version just needs to connect to the server). The contents of that datagram are ignored, so might as well specify that it should be empty.

Upvotes: 1

Martin James
Martin James

Reputation: 24887

One such use is to unblock a recvfrom() call when you wish to close a UDP service thread - set a 'terminate' flag and send the zero-length datagram on the localhost stack.

Upvotes: 2

Related Questions