socketsberkeley-sockets

How long are UDP datagrams stored in a socket?


I'm in openSUSE Linux (v15.1), using berkeley sockets.

I have a "sender" app that sends a datagram each second. Another "receiver" app that reads all the time. It works well.

But If I have both turned off, send some datagrams from the sender, turn it off... and then activate the receiver, nothing is there to be read. So the datagrams are gone.

I need this because I'm reading the datagrams at a given speed and I need to be sure that at least one of them stays there.

I found that there's a "receive buffer" set on the socket, and you can read and change information on input and output buffers using "getsockopt" and change them using "setsockopt".

But when I read the socket, even when I know there was something sent, there's nothing. So how long are the packages stored there?. I couldn't find any way to check or change this in "getsockopt" options.


Solution

  • The answer to your question is that the OS will not save any received packets unless you have an open socket. If you have an open socket, its buffer will be there for as long as the socket is open. A received packet for that socket will stay in the buffer until it is read.

    When you open a UDP socket with a specific address and port (using socket() and bind()), a buffer is created for that socket and linked to that specific address/port. The OS will save any incoming packets that match the address/port to that socket's buffer.

    While the receiver program is "off", there's no socket. So, although the OS might receive UDP packets, it can't match them to an open socket with an appropriate address/port, causing the packets to be discarded.

    When the receiver is "on", it will keep received packets in its buffer until it reads them. If the buffer fills up, new packets will be lost until buffer space is cleared up.

    I need this because I'm reading the datagrams at a given speed and I need to be sure that at least one of them stays there.

    UDP isn't reliable, which is sometimes exactly what you need (think of a telephone call, you would probably prefer to glitch the middle of a vowel or even a whole word than have the call pause while error-correcting itself).