Skip to content
Visual explainer 2h 30m to learn 4 steps

UDP sockets

Send and receive datagrams and handle loss and reordering.

By Invicly Tech, , in Linux System Programming. About 12 minutes to read.

Topic 34 of 42

In short

UDP sends independent datagrams with no connection, no ordering and no delivery guarantee. Each sendto is one datagram and each recvfrom returns exactly one, so message boundaries are preserved. It suits DNS, games, streaming and metrics, where low latency matters more than perfect reliability.

Explained simply

UDP is like sending postcards. Each one travels alone, with the address written on it. Most arrive, but some may get lost, some may arrive twice, and some may arrive in a different order. Nobody tells you which.

In exchange you get speed and simplicity. There is no call to set up, no waiting for lost packets to be resent, and each postcard arrives whole or not at all. That is perfect for things like DNS lookups, voice calls and online games, where a late answer is as bad as no answer.

In code, a server binds a socket and calls recvfrom, which gives one complete message plus the sender's address. It answers with sendto to that address. One sendto is always one message on the other side, never half of one.

If you need some reliability, you build just the part you need: a timeout and a retry for requests, a number on each message to spot duplicates or wrong order. That is exactly what DNS clients and game engines do.

Press Play on a diagram to walk through it one step at a time.

CompareTCP vs UDP
TCP
  • Connection set up by a handshake
  • Reliable, ordered byte stream
  • Flow and congestion control
  • Used by HTTP, SSH and databases
UDP
  • No connection, just datagrams
  • May be lost, duplicated or reordered
  • Message boundaries preserved
  • Used by DNS, QUIC, VoIP and games
LayersOne unfragmented UDP datagram on Ethernet (1500 MTU)
  1. 1
    Ethernet frame

    Carries at most 1500 bytes of IP packet

  2. 2
    IPv4 header: 20 bytes

    40 bytes for IPv6

  3. 3
    UDP header: 8 bytes

    Ports, length, checksum

  4. 4
    Payload: up to 1472 bytes

    1452 with IPv6; larger means fragments

In depth

Datagram boundaries and size limits

Each sendto creates one datagram, and each recvfrom returns exactly one. If your buffer is smaller than the datagram, the extra bytes are thrown away for good; they do not wait for your next call. On Linux, passing MSG_TRUNC to recv returns the real length even when it did not fit, which helps you size buffers.

The theoretical maximum payload is 65,507 bytes over IPv4 (65,535 minus the 20-byte IP header and the 8-byte UDP header). In practice the limit that matters is the path MTU, usually 1500 bytes on Ethernet. A larger datagram is split into IP fragments, and if any one fragment is lost, the whole datagram is lost. So staying within 1472 bytes of payload over IPv4 (1452 over IPv6) avoids fragmentation on plain Ethernet, and many protocols stay near 1200 bytes to be safe across tunnels and VPNs. QUIC, for example, requires paths to carry at least 1200 bytes.

Loss, duplicates and full buffers

UDP packets are lost on the network, but very often they are lost on the receiving machine. Each socket has a receive buffer. If datagrams arrive faster than your program calls recvfrom, the buffer fills and the kernel silently drops new ones. The sender never knows.

You can see these drops: nstat -az UdpRcvbufErrors or netstat -su (receive buffer errors). The fixes are to read faster (a dedicated thread, recvmmsg to grab many datagrams per call) and to give the socket a larger buffer with setsockopt SO_RCVBUF. The kernel caps that request at net.core.rmem_max, so raise the sysctl too.

UDP also has no congestion control. A sender that blasts as fast as it can will cause loss for itself and for everyone sharing the link. Real protocols limit their own rate.

  • nstat -az UdpRcvbufErrors counts drops on full receive buffers
  • sysctl net.core.rmem_max caps SO_RCVBUF
  • ss -ulmn shows each UDP socket's buffer use

Timeouts and retries

A request over UDP needs a timeout, or a lost packet makes the client wait forever. Two common ways: set SO_RCVTIMEO with a struct timeval, after which recvfrom fails with EAGAIN or EWOULDBLOCK when time is up, or wait with poll and a timeout in milliseconds.

When the timeout fires, send the request again, a limited number of times. Increase the wait each time (exponential backoff), for example 0.5, 1 and 2 seconds, so a busy server is not flooded with retries. Put a request ID in each message and check it on the reply. Otherwise a late reply to the first attempt may be taken as the answer to a different request. Finally, retries mean the server may see the same request twice, so requests should be idempotent: doing them twice must be harmless. DNS queries are read-only for this reason, and DNS clients retry exactly this way.

SequenceA request with timeout and retry
Client
Network
Server
  1. 1request id=7
    Client to Network: request id=7
  2. 2datagram lost
    Network to Network: datagram lost
  3. 3timeout after 0.5 s
    Client to Client: timeout after 0.5 s
  4. 4retry: request id=7
    Client to Server: retry: request id=7
  5. 5reply id=7
    Server to Client: reply id=7
  6. 6id matches: done
    Client to Client: id matches: done

Connected UDP sockets

Calling connect on a UDP socket sends nothing over the network. It only records a default peer. After that you can use send and recv instead of sendto and recvfrom, and the kernel drops datagrams from any other address, which is a cheap filter for clients.

There is a bonus. If the server is not running, the target host usually answers with an ICMP port unreachable message. On a connected socket, Linux reports that as ECONNREFUSED on a later send or recv, so the client fails fast instead of waiting for a timeout. Unconnected sockets do not get these errors by default.

A server talking to many clients keeps one unconnected socket and uses recvfrom and sendto, since it must reply to whoever wrote.

  • connect(udp_fd, ...) = set default peer, no handshake
  • ECONNREFUSED on a connected UDP socket means nothing listens there

UDP or TCP?

Choose TCP when you need every byte, in order, and do not want to write that logic yourself: web pages, file transfers, database connections, SSH. Choose UDP when timeliness beats completeness, or when the messages are tiny and independent. A voice call should skip a lost 20 ms of audio, not pause to resend it. DNS is one small question and one small answer, where a TCP handshake would double the wait. DHCP and NTP are other classic UDP protocols.

UDP is also the base for building your own transport. QUIC, which carries HTTP/3, runs over UDP and adds reliability, encryption and congestion control in user space, avoiding head-of-line blocking where one lost packet holds up every stream. Multicast and broadcast only exist for UDP.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Send with sendto and receive with recvfrom~40m
  2. 2
    Explain datagram boundaries and size limits~40m
  3. 3
    Handle loss with timeouts and retries~40m
  4. 4
    Compare UDP and TCP trade-offs~40m

Key points

  • One sendto is one datagram; recvfrom with a too-small buffer truncates it.
  • Keep datagrams under about 1200 to 1400 bytes to avoid IP fragmentation.
  • Add your own timeouts, retries and sequence numbers if you need reliability.
  • connect on a UDP socket just sets a default peer and filters incoming packets.

Key terms

Tap a card to flip it. 0/5 known

Examples

c
#include <netinet/in.h>
#include <sys/socket.h>

int main(void) {
  int s = socket(AF_INET, SOCK_DGRAM, 0);
  struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(9000), .sin_addr.s_addr = htonl(INADDR_ANY) };
  if (bind(s, (struct sockaddr *)&a, sizeof a) < 0) return 1;
  for (;;) {
    char buf[1500]; struct sockaddr_in peer; socklen_t len = sizeof peer;
    ssize_t n = recvfrom(s, buf, sizeof buf, 0, (struct sockaddr *)&peer, &len);
    if (n > 0) sendto(s, buf, n, 0, (struct sockaddr *)&peer, len);   // echo back
  }
}

UDP echo server; test with nc -u localhost 9000.

A UDP client with timeout and three retries

We send a request and wait up to 1 second for the reply, then retry with a doubled timeout. Step 1: connect the UDP socket to the server so we can use send and recv and get ECONNREFUSED if nothing listens. Step 2: for each attempt, set SO_RCVTIMEO and send. Step 3: recv returns -1 with EAGAIN or EWOULDBLOCK on timeout, and we try again. Step 4: any other result ends the loop. A real client would also check that the reply carries the right request ID.

c
ssize_t ask(int fd, const char *req, char *reply, size_t cap) {   /* fd is connected */
  for (int attempt = 0, ms = 1000; attempt < 3; attempt++, ms *= 2) {
    struct timeval tv = { .tv_sec = ms / 1000, .tv_usec = (ms % 1000) * 1000 };
    if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv) < 0) return -1;
    if (send(fd, req, strlen(req), 0) < 0) return -1;              /* e.g. ECONNREFUSED */
    ssize_t n = recv(fd, reply, cap, 0);
    if (n >= 0) return n;                                          /* one whole datagram */
    if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) return -1;
    fprintf(stderr, "timeout after %d ms, retrying\n", ms);
  }
  errno = ETIMEDOUT; return -1;
}

Finding datagrams dropped by a busy receiver

A metrics collector over UDP shows gaps, but the network looks healthy. Step 1: check the kernel counters; a rising UdpRcvbufErrors means the socket's receive buffer was full and the kernel dropped datagrams. Step 2: look at the socket itself with ss -ulmn, where the skmem field shows buffer use (rb is the buffer size). Step 3: raise the system cap and ask for a bigger buffer in the program with SO_RCVBUF. Step 4: if drops continue, the program is too slow; read in a dedicated thread or with recvmmsg.

bash
nstat -az UdpRcvbufErrors UdpInErrors
# UdpRcvbufErrors   18342   0.0      <- datagrams dropped on a full buffer
ss -ulmn 'sport = :8125'
# ... skmem:(r212992,rb212992,...)   r = bytes queued, rb = buffer size
sudo sysctl -w net.core.rmem_max=8388608
# in the program, before receiving:
#   int sz = 8 << 20; setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &sz, sizeof sz);

Quick reference

  • One sendto = one datagram; one recvfrom = one datagram or nothing
  • A too-small recv buffer silently truncates; recv(..., MSG_TRUNC) reports the real size
  • Max payload 65,507 bytes over IPv4; stay under 1472 (IPv4) or 1452 (IPv6) on Ethernet
  • SO_RCVTIMEO makes recvfrom fail with EAGAIN or EWOULDBLOCK on timeout
  • connect on UDP sets a default peer and enables ECONNREFUSED errors
  • nstat -az UdpRcvbufErrors shows drops from full receive buffers
  • Retries need request IDs and idempotent requests
  • nc -u host 9000 sends UDP lines; nc -ul 9000 listens

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A sender sends a 1000-byte datagram and the receiver calls recvfrom with a 600-byte buffer. What happens to the last 400 bytes?

Question 2

2Why do many UDP protocols keep datagrams around 1200 to 1400 bytes?

Question 3

3A UDP server drops datagrams under load, but the network has no errors. What should you check first?

Question 4

4What does connect do on a UDP socket?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Start the explainer's UDP echo server and send it lines with nc -u. Then send one datagram bigger than its 1500-byte buffer and see what comes back.

  2. Exercise 2medium

    Write a UDP client that sends a numbered PING every 100 ms for 50 pings and counts how many replies come back from the echo server, ignoring replies with the wrong number.

  3. Exercise 3hard

    Add de-duplication to a UDP server: clients send "id payload", the server performs each id only once, and replies to repeats with the cached answer.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is UDP faster than TCP?
It has less overhead and no handshake or retransmission waits, so latency is lower. For bulk transfer TCP is usually just as fast, and it handles loss and congestion for you.
Can UDP packets arrive out of order on localhost?
Practically never on loopback, and rarely on a simple LAN. On the internet reordering and loss do happen, so test with tc netem to add loss and delay.
Why does HTTP/3 use UDP?
QUIC runs over UDP so it can be deployed in user space without changing operating systems, and it avoids TCP head-of-line blocking by handling each stream separately.
Do I need to call htons for UDP ports too?
Yes. sockaddr_in and sockaddr_in6 always hold the port in network byte order, whatever the protocol.

Go deeper

ShareXLinkedInWhatsApp