12. UDP: Datagrams Between Programs

The thinnest possible transport: ports to find the right program, a length, a checksum, and nothing else, and why DNS, games, voice calls and QUIC want exactly that

Imagine a big apartment block with a single street address. The postal service is very good at getting envelopes to the building: that's all the street address is for. But two hundred people live inside, so every envelope also carries a flat number, and the caretaker in the lobby uses it to drop each envelope into the right letterbox.

Now imagine the cheapest way to use that system: postcards. You write a few lines, put the building's address and a flat number on the front, and drop it in a postbox. There's no tracking number and no signature on delivery. If you send three postcards on Monday, they might arrive Wednesday, Tuesday and never. You won't be told about the one that went missing, and the caretaker throws away anything addressed to an empty flat. But postcards are quick, there's no paperwork, and for a lot of messages ("What's the number for the plumber?") that's all you need. If no answer comes, you just send another.

That's UDP, the User Datagram Protocol. IP is the postal service: it gets packets to the right machine. UDP adds the flat number, a 16-bit port that gets each message to the right program, plus a length and a checksum. That's the whole protocol. Everything else you might want from a network, such as delivery receipts, ordering and not overwhelming the recipient, is left to the application.

This page follows one small UDP message all the way: the laptop asking its resolver for the address of example.com. By the end you'll be able to read every byte of it, compute its checksum by hand, and explain why the protocol that carries most of the world's DNS, voice calls, game traffic and, increasingly, web traffic is the one that promises almost nothing.

The Transport Layer's Job

Every article in this series so far has been about getting a packet to the right host. Ethernet and ARP handle one link, IP and the routing protocols handle the path, and by the end of BGP a packet from our laptop could reach any address on the Internet. But a host isn't the final destination. Our laptop is running a browser, a mail client, a chat app, a DNS resolver library and a dozen background services, all at once, all sharing one IP address. When a packet arrives, which of them is it for?

That's the transport layer's first job: process-to-process delivery on top of IP's host-to-host delivery. In the layer model it sits between IP and the applications, and the Internet has two classic answers:

UDP: the minimum

Ports to pick the program, a length, and a checksum. Each message is sent on its own, as a datagram. No setup, no acknowledgements, no ordering, no retransmission. Defined in RFC 768: three pages.

TCP: the full service

Ports, plus a connection with a handshake, a reliable and ordered byte stream, retransmission, flow control and congestion control. Defined in RFC 793 (1981), now RFC 9293: close to a hundred pages.

UDP's specification, RFC 768, was written by Jon Postel and published on 28 August 1980. It's one of the shortest standards the Internet runs on. It exists because of a design decision taken a couple of years earlier: the original Transmission Control Program did everything, routing and reliability, in one protocol, and in 1978 it was split into IP for getting packets across networks and TCP for reliability on top. Part of the argument for the split came from people experimenting with packet voice, who pointed out that a voice call can't afford to wait for a lost packet to be resent. Once IP stood on its own, applications that didn't want TCP's guarantees needed a way to reach a program without them. UDP is that way, and it's barely more than IP with ports.

In the IPv4 header's Protocol field (and IPv6's Next Header), UDP is number 17, 0x11. TCP is 6, as in the 95-byte frame we took apart at the start of the series.

Ports and Sockets

A port is a 16-bit number, 0 to 65535, that names one endpoint inside a host. Every UDP datagram carries two: a source port, identifying the sending program, and a destination port, identifying the program that should receive it. Together with the two IP addresses in the IP header, they say exactly which program on which machine is talking to which program on which other machine.

Who gets which number

Servers listen on fixed, published ports, so clients know where to find them: DNS on 53, DHCP servers on 67, NTP on 123. Clients don't need fixed ports, because the server simply replies to whatever source port the request came from. So the client's operating system picks a free one for each new socket, an ephemeral port that lives only as long as the socket does.

IANA keeps the registry and, since RFC 6335 (2011), divides it in three:

Range IANA name Examples
0–1023 System, or well-known 53 DNS, 67/68 DHCP, 69 TFTP, 123 NTP, 161 SNMP, 443 QUIC
1024–49151 User, or registered 1194 OpenVPN, 3478 STUN, 5060 SIP, 5353 mDNS
49152–65535 Dynamic, or private Ephemeral client ports, by IANA's book

Many protocols are registered for both UDP and TCP on the same number (DNS uses both on 53), but the two port spaces are completely separate: UDP port 53 and TCP port 53 are different endpoints, as unrelated as flat 53 in two different buildings.

Not every operating system follows IANA's suggestion for ephemeral ports. Windows (since Vista) and macOS use 49152–65535, but Linux's default ip_local_port_range is 32768–60999, about 28,000 ports. It applies to TCP and UDP alike and, despite living under net.ipv4, to IPv6 too. (It was 32768–61000 until 2015, when the upper end was nudged to 60999 so the range has an even number of ports, which helps the kernel's port allocator.) Ports below 1024 are traditionally privileged: on Linux, binding to one needs root or the CAP_NET_BIND_SERVICE capability. Port 0 is reserved and never appears on the wire; asking the kernel to bind to port 0 means "pick one for me".

Sockets and the five-tuple

A program doesn't send UDP datagrams by writing headers itself. It asks the operating system for a socket, an endpoint the kernel manages on its behalf, optionally binds it to a local address and port, and then sends and receives through it. Here's the laptop's DNS lookup at the socket level, in Python:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)   # SOCK_DGRAM = UDP
s.settimeout(2.0)
query = bytes.fromhex("9f3c01000001000000000000"           # DNS header
                      "076578616d706c6503636f6d00"         # example.com
                      "00010001")                         # type A, class IN
s.sendto(query, ("192.168.10.1", 53))   # kernel picks the source port
reply, sender = s.recvfrom(1232)        # one whole datagram, or a timeout

The program never mentioned a source port, so the kernel chose one at the first sendto. On our Linux laptop it picked 41853: inside Linux's range, though outside IANA's. A conversation over UDP is then identified by five values, the five-tuple:

The laptop's DNS query, as a five-tuple

protocol   UDP (17)
source     192.168.10.10 : 41853    the laptop, an ephemeral port
dest       192.168.10.1  : 53       R1, the home router, which runs a DNS forwarder

The laptop's resolver is R1 itself. Home routers almost always run a small caching DNS forwarder and tell their clients to use it, which is what our router's Router Advertisements did in the IPv6 article. R1 asks the wider Internet on the laptop's behalf.

Demultiplexing: which socket gets it?

When a UDP datagram arrives, the receiving kernel has to find the socket it belongs to. That step is called demultiplexing, and it's the caretaker sorting the post. Unlike TCP, where every connection is a distinct five-tuple, a UDP socket can be bound loosely or tightly:

  • Unconnected: bound only to a local port, and perhaps a local address. It accepts datagrams from anyone, and recvfrom tells the program who each one came from. A DNS server's socket on port 53 works like this.
  • Connected: the program has also called connect() with a remote address and port. Nothing is sent; the kernel just remembers the peer, uses it as the default destination, and from then on only accepts datagrams from that one address and port. Many DNS client libraries, including glibc's, connect their sockets this way.

The kernel picks the most specific socket that matches. Here's the laptop, with four UDP sockets open:

Arriving datagrams Laptop 192.168.10.10 192.168.10.1:67 → :68 192.168.10.11:5353 → 224.0.0.251:5353 192.168.10.1:53 → :41853 203.0.113.80:443 → :52114 … → :9 UDP 68 · DHCP client unconnected, any sender UDP 5353 · mDNS responder unconnected, joined group 224.0.0.251 UDP 41853 · DNS lookup connected to 192.168.10.1:53 only UDP 52114 · browser (HTTP/3) connected to 203.0.113.80:443 only no socket on port 9 → reply with ICMP port unreachable

Notice what the connected socket on 41853 buys. If a datagram arrived for port 41853 from anywhere other than 192.168.10.1:53, it wouldn't match, no other socket would either, and the kernel would treat it exactly like a datagram to a closed port. That matters for DNS security. An attacker who wants to slip a forged answer into a lookup has to guess the query's 16-bit ID and, since Dan Kaminsky's cache-poisoning attack made headlines in 2008, the randomly chosen source port as well. Picking ephemeral ports at random, rather than counting up, turned a 1-in-65,536 guess into a single guess with odds of more than a billion to one.

In pseudocode, the kernel's input path is short:

def udp_input(ip, dgram):
    if not checksum_ok(ip, dgram):
        return                                  # silently dropped
    best = None
    for sock in sockets_bound_to(dgram.dst_port):
        if sock.local_ip not in (ANY, ip.dst):
            continue
        if sock.connected and sock.peer != (ip.src, dgram.src_port):
            continue
        best = more_specific(best, sock)        # connected beats unconnected
    if best:
        best.queue.append((ip.src, dgram.src_port, dgram.payload))
    elif is_unicast(ip.dst):
        send_icmp_port_unreachable(ip, dgram)   # see below
    # broadcast or multicast to a closed port: drop, say nothing

(For multicast and broadcast, every matching socket gets its own copy, not just the best one. We'll come back to that.)

Here's the entire UDP header. Every UDP datagram ever sent starts with these four 16-bit fields, big-endian, and nothing else:

bit 0 16 31 Source port (2) a3 7d = 41853 Destination port (2) 00 35 = 53 Length (2) 00 25 = 37 bytes Checksum (2) 57 eb Data here: a 29-byte DNS query for example.com Header: always 8 bytes. No options, no flags, no header-length field. Length counts header + data, so its minimum is 8 and its maximum 65,535.
Bytes Field Meaning
0–1 Source port The sender's port, where replies should go. Optional: 0 means "no reply expected".
2–3 Destination port The receiving program
4–5 Length Header plus data, in bytes: at least 8
6–7 Checksum Covers a pseudo-header, the UDP header and the data. In IPv4, 0 means "not computed".

The length field is technically redundant: the IP header already says how long the packet is, and the receiver can subtract. RFC 768 includes it anyway, and it earns its keep in the checksum, as we'll see. A receiver treats a datagram whose UDP length doesn't fit inside the IP packet as broken and drops it.

The whole packet, byte by byte

Here's the laptop's query as it leaves the network card, minus the Ethernet header and trailer (which are the same as in the ARP and Routing Basics articles: from …aa:bb:01 to R1's …cc:dd:02, EtherType 0800). Every value is real, including both checksums, which were computed for these exact bytes.

Hex dump: a 57-byte IPv4 packet

0000  45 00 00 39 5c 21 40 00 40 11 49 37 c0 a8 0a 0a  E..9\!@[email protected]....
0010  c0 a8 0a 01 a3 7d 00 35 00 25 57 eb 9f 3c 01 00  .....}.5.%W..<..
0020  00 01 00 00 00 00 00 00 07 65 78 61 6d 70 6c 65  .........example
0030  03 63 6f 6d 00 00 01 00 01                       .com.....

 IPv4  bytes 0–19 ·  UDP header  bytes 20–27 ·  DNS query  bytes 28–56

Read it the way R1's kernel does:

  1. Offset 0x00: IPv4

    45: version 4, 20-byte header. Total length 00 39 = 57. 40 00: Don't Fragment. TTL 40 = 64. Protocol 11 = 17, UDP. Header checksum 49 37. Source c0 a8 0a 0a = 192.168.10.10, destination c0 a8 0a 01 = 192.168.10.1, one of R1's own addresses, so the packet is for R1 itself.

  2. Offset 0x14: UDP

    Source port a3 7d = 41853. Destination port 00 35 = 53: DNS. Length 00 25 = 37, which is 57 − 20, so it agrees with IP. Checksum 57 eb, verified below. R1's kernel finds its DNS forwarder's socket on port 53 and queues the 29 bytes that follow.

  3. Offset 0x1c: the DNS query

    Query ID 9f 3c, flags 01 00 ("recursion desired"), one question and no records. Then the name as length-prefixed labels: 07 example 03 com 00. Then type 00 01 (A, an IPv4 address) and class 00 01 (Internet). The DNS article takes this format apart properly.

That's 8 bytes of transport header for 29 bytes of question. Compare TCP, which would need a 20-byte header, plus a three-way handshake before the question and a four-way goodbye after. R1's answer comes back the same way with the ports swapped, from 192.168.10.1:53 to 192.168.10.10:41853: a 45-byte DNS message (the question again, plus a 16-byte answer record), so a UDP length of 53. In our documentation-address world, the answer is 203.0.113.80, the web server from the earlier articles. (The real example.com lives elsewhere.)

Simplified on purpose

A real resolver library would usually add an 11-byte EDNS(0) record to the query (more on that in How Big Can a Datagram Be?), and modern ones often add a DNS cookie too. We've left them out to keep the arithmetic short. The UDP header itself is exactly as it would be.

The Checksum

The UDP checksum is the same 16-bit Internet checksum we computed for the IPv4 header in Layers & Encapsulation and for a RIP update in Distance-Vector Routing. What's different is what it covers.

The pseudo-header

IP routes a packet using its addresses, and a bit flip in a destination address could deliver a perfectly intact UDP datagram to the wrong machine, or a flip in the Protocol field could hand a TCP segment to UDP. To catch that, the UDP checksum covers not just the datagram but a pseudo-header built from the IP header's fields. It is never sent; sender and receiver each construct it in memory, put it in front of the datagram, and checksum the lot:

bit 0 8 16 31 Source IPv4 address (4) · c0 a8 0a 0a = 192.168.10.10 Destination IPv4 address (4) · c0 a8 0a 01 = 192.168.10.1 Zero 00 Protocol 11 = 17 UDP length (2) · 00 25 = 37 UDP header (8), checksum field set to 00 00 while computing Data (29), plus one zero byte of padding to make whole 16-bit words Dashed: the pseudo-header exists only inside the checksum calculation, never on the wire.

It's a layering violation, deliberately: the transport layer reaching down to check the network layer's addressing. That's also why a NAT that rewrites the source address has to fix the UDP checksum as well as the IP one, even though it never touches a UDP header field. (If it rewrites the port too, it has two reasons.)

Ones'-complement addition

The arithmetic is ones'-complement addition of 16-bit words: add them as ordinary numbers, and whenever the sum carries out of the top bit, add that carry back in at the bottom. This is the end-around carry. For example, f000 + 2000 = 1 1000; the carry 1 wraps round, giving 1000 + 1 = 1001.

In practice nobody wraps the carry after every addition. You add all the words into a wider accumulator and fold the carries back in once at the end, which RFC 1071 shows gives the same result. Then you flip every bit, and that's the checksum:

  1. Lay out the words

    Pseudo-header, then UDP header with the checksum field as 0000, then the data. If the data has an odd number of bytes, pad it with one zero byte at the end, for the sum only. The pad isn't sent, and it isn't counted in the length.

  2. Add them all

    As ordinary unsigned numbers, in a 32-bit (or wider) accumulator.

  3. Fold

    Add the bits above 16 back into the low 16 bits, and repeat until nothing is left above bit 15.

  4. Complement

    Flip every bit. If the result is 0000, send ffff instead.

Worked example: the laptop's query

Our DNS query has 29 bytes of data, an odd number, so its last word is 01 followed by a pad byte: 0100.

The six pseudo-header words:

c0a8+0a0a+c0a8+ 0a01+0011+0025= 19591\begin{aligned} & \texttt{c0a8} + \texttt{0a0a} + \texttt{c0a8} \\ +\ & \texttt{0a01} + \texttt{0011} + \texttt{0025} \\ =\ & \texttt{19591} \end{aligned}

The four UDP header words, with the checksum as zero:

a37d+0035+ 0025+0000= a3d7\begin{aligned} & \texttt{a37d} + \texttt{0035} \\ +\ & \texttt{0025} + \texttt{0000} \\ =\ & \texttt{a3d7} \end{aligned}

The fifteen words of DNS data, ending with the padded 0100:

9f3c+0100+0001+0000+ 0000+0000+0765+7861+ 6d70+6c65+0363+6f6d+ 0000+0100+0100= 26ea8\begin{aligned} & \texttt{9f3c} + \texttt{0100} + \texttt{0001} + \texttt{0000} \\ +\ & \texttt{0000} + \texttt{0000} + \texttt{0765} + \texttt{7861} \\ +\ & \texttt{6d70} + \texttt{6c65} + \texttt{0363} + \texttt{6f6d} \\ +\ & \texttt{0000} + \texttt{0100} + \texttt{0100} \\ =\ & \texttt{26ea8} \end{aligned}

The total is 19591+a3d7+26ea8=4a810\texttt{19591} + \texttt{a3d7} + \texttt{26ea8} = \texttt{4a810}. Fold the carry: a810+4=a814\texttt{a810} + \texttt{4} = \texttt{a814}. Flip every bit: ¬ a814=57eb\lnot\,\texttt{a814} = \texttt{57eb}. That's the value in bytes 6–7 of the UDP header.

Notice that the UDP length, 0025, appears twice: once in the pseudo-header and once in the real header. That's the redundant length field earning its keep.

Checking it

The receiver doesn't recompute and compare. It adds up everything, pseudo-header, header including the checksum, and data, and folds. The sender chose the checksum to be the ones'-complement negative of everything else, so for an intact datagram the total is "negative zero":

4a810+57eb=4fffb\texttt{4a810} + \texttt{57eb} = \texttt{4fffb}, and folding gives fffb+4=ffff\texttt{fffb} + \texttt{4} = \texttt{ffff}. Anything other than ffff\texttt{ffff} means the datagram, or the addresses it came with, changed on the way.

A datagram that fails the check is dropped silently. There's no error message and no retransmission: as far as the application is concerned, it was simply lost.

Zero means "no checksum", so zero becomes ffff

In IPv4, the UDP checksum is optional. A sender that doesn't want to compute one sends 0000, and the receiver skips the check. This was meant for debugging and for applications that do their own checking, and it was a real saving on 1980s hardware.

That creates a puzzle: what if the computed checksum genuinely is 0000? RFC 768's answer is to send ffff instead. In ones'-complement arithmetic, 0000 and ffff are two ways of writing zero, "positive zero" and "negative zero", so the receiver's sum folds to ffff either way.

When the checksum comes out as zero

Suppose the laptop had picked query ID f727 instead of 9f3c. That word is 57eb bigger, so the total becomes 4a810 + 57eb = 4fffb, which folds to ffff. Its complement is 0000, which would mean "no checksum", so the laptop sends ff ff in bytes 6–7. The receiver adds that ffff to the same total: 4fffb + ffff = 5fffa, which folds to fffa + 5 = ffff. Check passed.

IPv6: a bigger pseudo-header, and no opting out

IPv6 dropped the IP header checksum altogether (see the IPv6 header), so the transport checksum is the only thing guarding the addresses. RFC 8200 therefore makes the UDP checksum mandatory over IPv6: receivers must discard datagrams with a zero checksum. The pseudo-header grows to hold 128-bit addresses:

Bytes Field Our query over IPv6
0–15 Source address 2001:db8:1234:10:0:ff:feaa:bb01
16–31 Destination address 2001:db8:1234:10::1 (R1)
32–35 Upper-layer length (32 bits) 00 00 00 25 = 37
36–38, 39 Zero, then next header 00 00 00 · 11 = 17

Send the same 29-byte query from the laptop's IPv6 address to R1's, from the same port, and only the pseudo-header changes:

The twenty pseudo-header words:

2001+0db8+1234+0010+ 0000+00ff+feaa+bb01+ 2001+0db8+1234+0010+ 0000+0000+0000+0001+ 0000+0025+0000+0011= 23adb\begin{aligned} & \texttt{2001} + \texttt{0db8} + \texttt{1234} + \texttt{0010} \\ +\ & \texttt{0000} + \texttt{00ff} + \texttt{feaa} + \texttt{bb01} \\ +\ & \texttt{2001} + \texttt{0db8} + \texttt{1234} + \texttt{0010} \\ +\ & \texttt{0000} + \texttt{0000} + \texttt{0000} + \texttt{0001} \\ +\ & \texttt{0000} + \texttt{0025} + \texttt{0000} + \texttt{0011} \\ =\ & \texttt{23adb} \end{aligned}

The UDP header and data sum to a3d7\texttt{a3d7} and 26ea8\texttt{26ea8}, as before.

Total 54d5a\texttt{54d5a}. Fold: 4d5a+5=4d5f\texttt{4d5a} + \texttt{5} = \texttt{4d5f}. Flip: ¬ 4d5f=b2a0\lnot\,\texttt{4d5f} = \texttt{b2a0}.

So the IPv6 datagram is a3 7d 00 35 00 25 b2 a0 followed by the identical 29 bytes. Same ports, same length, same data, different checksum, because the checksum vouches for the addresses too.

The one exception is tunnelling. Protocols that wrap whole packets in UDP, where the inner packet has its own checks, may switch on a zero-checksum mode for their specific ports (RFC 6935 and RFC 6936), because computing a checksum over every byte of a tunnelled packet at line rate is expensive.

What the checksum can't do

The Internet checksum is weak. It can't detect two 16-bit words being swapped, or a 0000 word turning into ffff, and errors that cancel out slip through. Ethernet's CRC-32 catches far more on each link, so the UDP checksum's real job is to catch damage that happens inside routers and hosts, between the links, plus misdelivery via the pseudo-header. Applications that really care about integrity add their own check (and anything encrypted, like QUIC, gets a strong one for free from its authentication tag). The Checksums & CRC article shows exactly what this kind of sum can and can't catch.

Addresses and ports

Payload

The datagram


      

Pseudo-header, never sent

Built in memory by sender and receiver from the IP header’s fields, checksummed, and thrown away.


      

The checksum

Every 16-bit word, in order, with the running total:

What UDP Doesn't Do

The header is the whole protocol. There's no state machine, no timers and no handshake. That means UDP gives you none of the following:

  • No connection. The first datagram is just sent. There's no handshake to learn whether the other side exists, is listening, or wants to talk. (A "connected" UDP socket is purely a local convenience; the other side never knows.)
  • No delivery guarantee. A datagram lost to a full router queue, a failed checksum or a dead link is gone. Nobody resends it, and nobody tells the sender.
  • No ordering. Datagrams that take different paths, or get stuck behind different queues, arrive in whatever order they arrive.
  • No duplicate protection. A link-layer retry or a misbehaving middlebox can deliver one datagram twice, and UDP passes both up.
  • No flow control. Nothing stops a fast sender from overrunning a slow receiver. When a socket's receive buffer is full, the kernel drops new datagrams for it on the floor (Linux counts them as RcvbufErrors in /proc/net/snmp).
  • No congestion control. UDP will happily send as fast as the program calls sendto, whether or not the network can carry it.

That last one is the dangerous one. A TCP sender backs off when it sees loss, which is how a shared network stays usable (the Congestion Control article is about exactly that). A UDP application that doesn't back off just keeps pushing, and its packets crowd out everyone else's. RFC 8085, the IETF's UDP usage guidelines, says applications should control their sending rate and react promptly to signs of congestion. UDP leaves it to them.

Why Anyone Wants That

Every missing feature is something an application doesn't have to pay for. TCP's guarantees cost a round trip to set up, extra round trips to recover loss, and a strict ordering that makes everything wait for the slowest packet. For a lot of traffic, those costs are worse than the problem they solve.

DNS: one question, one answer

A DNS lookup is a single small question and a single small answer. Over UDP, it takes one round trip. Over TCP, it would take a handshake round trip first, then the query, and the server would have to keep connection state for millions of clients that each ask one question. If the UDP query or the answer is lost, the client just asks again after a timeout (a few seconds), and since the question is harmless to repeat, nothing breaks. The query ID pairs answers with questions. That's application-level reliability in its simplest form: timeout and retry.

DNS does use TCP when it has to, for answers too big for a datagram and for zone transfers, and DNS over TLS and HTTPS run on TCP or QUIC. But the bulk of the world's lookups is still plain UDP on port 53.

DHCP: you don't have an address yet

A laptop joining a network has no IP address, doesn't know the router or the DHCP server, and can't open a TCP connection to anybody. What it can do is shout. It sends a DHCPDISCOVER over UDP from 0.0.0.0 port 68 to the broadcast address 255.255.255.255 port 67, and any DHCP server on the link can answer. TCP has no way to talk to "whoever is out there". The DHCP article follows that exchange.

Voice, video and games: late is the same as lost

On a voice call, each packet carries 10 or 20 milliseconds of sound. If one is lost, TCP would hold back every packet behind it until the retransmission arrived, a full round trip later. By then the moment has passed: the listener hears a stall, then a burst. A voice app would much rather play a brief gap, or have its codec smooth over it, and keep going. Games are the same. If the server sends the positions of every player 60 times a second, a lost update is simply superseded by the next one, and waiting for it would be actively harmful.

That waiting has a name: head-of-line blocking. A byte stream must be delivered in order, so one missing segment blocks everything behind it, even data that has already arrived. UDP can't have head-of-line blocking, because there's no line. RTP, the protocol carrying the media in most voice and video calls (RFC 3550), runs on UDP, adding its own sequence numbers and timestamps so the receiver can spot gaps and play audio at the right pace.

QUIC: building a better TCP on top of UDP

The most important UDP traffic today may be the kind that is reliable. QUIC (RFC 9000, May 2021) is a complete transport protocol, with connections, reliable ordered streams, congestion control and built-in TLS 1.3 encryption, that runs inside UDP datagrams, usually on port 443. HTTP/3 runs on QUIC, and most large websites and browsers now speak it.

Why put a reliable protocol inside an unreliable one rather than improve TCP?

  • Deployability. TCP lives in operating system kernels, and the Internet is full of firewalls and NATs that inspect TCP headers and break on anything unfamiliar (see Real networks bend the rules in the first article). A new IP protocol number would be blocked almost everywhere. UDP gets through nearly everything, and QUIC can ship inside an application and update every few weeks.
  • No head-of-line blocking between streams. A web page loads dozens of resources over one connection. In QUIC each is its own stream, and a lost packet only stalls the stream it belonged to.
  • Faster setup. The transport and TLS handshakes are combined, so a new connection needs one round trip, and a repeat connection can send data in the very first packet.
  • Encryption of its own headers. Almost all of QUIC's header is encrypted, so middleboxes can't meddle with it, and future versions can change it.

UDP is the right foundation precisely because it does so little: it gets QUIC's packets to the right program and gets out of the way. The same reasoning puts VPNs like WireGuard and OpenVPN on UDP, and the VXLAN overlay networks from the VLANs article: when you're tunnelling packets that already have their own transport inside, a second layer of reliability underneath would only fight with it.

Message Boundaries: Datagrams, Not a Stream

There's one more difference between UDP and TCP that's easy to miss and bites almost everyone once. UDP preserves message boundaries; TCP doesn't.

UDP: datagrams

The sender calls sendto twice, with 100 bytes and then 200. The receiver's first recvfrom returns exactly the 100-byte message and the second exactly the 200-byte one (if both arrive, in whatever order they arrive). One send is one datagram is one receive. A message is never split, merged or delivered half-way.

TCP: a byte stream

The sender writes 100 bytes and then 200. The receiver might read 300 bytes at once, or 50 then 250, or anything else. TCP delivers bytes in order but knows nothing about where the sender's messages began and ended, so applications add their own framing: a length prefix, or a delimiter like HTTP/1.1's blank line.

That makes UDP pleasantly simple for request-and-reply protocols: one datagram is one complete message, and the application never has to reassemble anything. The catch is on the receiving side: recvfrom must be given a buffer big enough for the whole datagram. If the buffer is too small, the rest of the datagram is discarded, not saved for the next call (on Linux the MSG_TRUNC flag tells you it happened). That's why our Python example asked for 1232 bytes, not a handful.

How Big Can a Datagram Be?

The length field is 16 bits, so a UDP datagram, header included, can be at most 65,535 bytes, which would leave 65,527 for data. But the datagram has to fit inside an IP packet, and an IPv4 packet's Total Length field is 16 bits too and includes the IP header. So the real limit over IPv4 is:

65,535−20−8=65,50765{,}535 - 20 - 8 = 65{,}507

That is 65,535 bytes, minus 20 for the IPv4 header and 8 for the UDP header: 65,507 bytes of data.

(Less if the IPv4 header carries options.) IPv6's Payload Length doesn't count its own 40-byte header, so over IPv6 the full 65,527 bytes are available. IPv6 even has jumbograms (RFC 2675) for links that can carry more, in which case the UDP length field is set to zero and the real length comes from an IPv6 extension header. They're a curiosity in practice.

What fits in one frame

None of that means sending 65 KB datagrams is a good idea. An Ethernet link's MTU is 1500 bytes, so the biggest datagram that fits in one frame is:

Over IPv4 Over IPv6
MTU 1500 1500
− IP header − 20 − 40
− UDP header − 8 − 8
Largest unfragmented payload 1472 1452

Anything bigger has to be fragmented: split by IP into several packets that are glued back together at the destination. A full-size 65,507-byte datagram over IPv4 becomes 65,515 bytes of IP payload, carried 1480 bytes per fragment (fragment sizes must be multiples of 8): 44 full fragments and one of 395 bytes, 45 fragments in all.

Fragmentation makes UDP's unreliability much worse:

  • Lose one fragment, lose everything. There's no partial delivery. If each fragment has a 1% chance of being lost, the whole datagram survives with probability 0.9945 ≈ 64%, and nothing tells the sender which part went missing.
  • Only the first fragment carries the UDP header. The others have no ports, so firewalls and NATs that filter or translate by port can't handle them without reassembling first, and many simply drop them.
  • IPv6 routers never fragment. Only the sending host can, after learning the path MTU from ICMPv6 Packet Too Big messages, which some networks block (the PMTU black hole from Routing Basics).

So well-behaved UDP applications keep their datagrams small. DNS is the textbook case. RFC 1035 (1987) limited UDP answers to 512 bytes; anything bigger set the TC ("truncated") flag and the client retried over TCP. EDNS(0) (RFC 6891) lets a client advertise a larger buffer, and in 2020 the operators behind DNS Flag Day settled on a default of 1232 bytes: IPv6's minimum MTU of 1280, minus 40 and 8, which fits on any IPv6 path without fragmenting. QUIC goes the other way and requires the path to carry datagrams of at least 1200 bytes, refusing to run otherwise.

When Nobody Is Listening

TCP finds out immediately if nothing is listening: the server's kernel answers a connection attempt with a reset. UDP has no connection attempt, so what happens to a datagram for a closed port?

The receiving host answers with ICMP Destination Unreachable, code 3: port unreachable (ICMPv6 type 1, code 4), which we met in Routing Basics. Like every ICMP error, it carries the start of the offending packet, at least the IP header plus 8 bytes, which is exactly enough to include the whole UDP header with both ports. That's how the sender works out which of its sockets the error is about.

Suppose someone mistyped the laptop's resolver as 203.0.113.80, the web server, instead of 192.168.10.1. The query goes out through R1's NAT, arrives at a machine that doesn't run DNS, and comes straight back as an error:

Laptop 192.168.10.10 R1 (NAT) WAN 198.51.100.23 Web server 203.0.113.80 ① UDP → 203.0.113.80:53 from 192.168.10.10:41853 ② UDP → 203.0.113.80:53 from 198.51.100.23:41853 ③ no socket on UDP 53 ④ ICMP 3/3 port unreachable quotes …23:41853 → …80:53 ⑤ ICMP 3/3, quote rewritten to 192.168.10.10:41853 ⑥ recv() fails: ECONNREFUSED
  1. Out through the NAT

    R1 rewrites the source to its public 198.51.100.23, keeping port 41853 because it's free, records the mapping, and fixes both checksums.

  2. The server has nothing on UDP port 53

    Its kernel runs the lookup from earlier, finds no socket, and sends ICMP type 3, code 3 back to 198.51.100.23, quoting the query's IP and UDP headers.

  3. R1 translates the error too

    The ICMP message itself has no ports, so R1 looks inside it, finds the quoted UDP header with source port 41853, matches it to the mapping, and rewrites both the outer destination and the quoted source back to 192.168.10.10. NATs that forget this step make UDP errors vanish.

  4. The laptop's socket gets the news

    The laptop's kernel reads the quoted ports, finds the connected socket on 41853, and makes its next recv fail with ECONNREFUSED, "connection refused", even though there never was a connection. The resolver library gives up on that server at once, instead of waiting for a timeout.

Two caveats make this signal unreliable, in keeping with everything else about UDP:

  • Only connected sockets hear about it. On Linux, an unconnected socket gets no error at all by default, because the kernel can't be sure the program cares about that particular destination. (A program can opt in with the IP_RECVERR socket option.)
  • Many hosts never send it. Firewalls usually drop datagrams to closed ports without a word, and operating systems rate-limit their ICMP errors. So silence proves nothing: a closed port, a firewall, a lost datagram and a slow server all look the same from outside.

Traceroute relies on exactly this message: its UDP probes go to unlikely high ports, and a port unreachable is how it knows it has reached the destination.

Broadcast and Multicast

A TCP connection is a conversation between exactly two endpoints. Its handshake, sequence numbers and acknowledgements make no sense with an unknown number of receivers, so TCP simply can't be sent to a broadcast or multicast address. UDP can, because a datagram doesn't care who, or how many, receive it. Every one-to-many protocol on an IP network runs over UDP (or directly over IP, like OSPF):

Name Sent to Why
DHCP 255.255.255.255:67, broadcast The client has no address and doesn't know the server's
mDNS 224.0.0.251 or ff02::fb, port 5353 Printers and speakers announce themselves to the whole link
RIP 224.0.0.9 or ff02::9, ports 520, 521 Routing updates to every neighbour at once
SSDP 239.255.255.250:1900 Home devices discovering each other (UPnP)

When a broadcast or multicast datagram arrives, the kernel gives a copy to every socket bound to that port that has joined the group, so several programs can listen to mDNS at once (they set SO_REUSEADDR or SO_REUSEPORT to share the port). And a host never answers a broadcast or multicast datagram with a port unreachable, even if no one is listening: a hundred hosts each complaining about one packet would be a storm of their own.

IPv6 has no broadcast at all; its link-wide jobs use multicast groups like ff02::1 instead, as the IPv6 article showed. Broadcasts never cross a router, and multicast only does where routers run a multicast routing protocol, which is rare outside campus and provider networks. Remember too that a VLAN is a broadcast domain: DHCP and mDNS on VLAN 10 never reach VLAN 20 unless the router relays them.

UDP Through NATs and Firewalls

A stateful firewall or NAT has an easy job with TCP: it watches the SYN, SYN-ACK, FIN and RST flags and knows exactly when each connection starts and ends. UDP has no flags. So R1 has to guess, by keeping pseudo-state: when a datagram goes out, it creates a mapping and allows replies from that remote address and port, and when nothing has been seen for a while, it assumes the conversation is over and forgets.

Take the laptop's browser fetching a page over HTTP/3. Its first QUIC packet leaves from 192.168.10.10:52114 for 203.0.113.80:443, and R1 records:

R1's NAT table entry

proto  inside               outside               remote             expires
udp    192.168.10.10:52114  198.51.100.23:52114   203.0.113.80:443   in 30 s

Packets from 203.0.113.80:443 to 198.51.100.23:52114 are translated back to the laptop. Each packet in either direction resets the timer.

How long should the timer be? Too short, and a quiet but live conversation (a voice call during a pause, a game lobby) gets cut off; too long, and the table fills with dead entries. The requirements and the defaults don't agree:

  • RFC 4787 (2007) says a NAT's UDP mapping must not expire in less than two minutes, except for specific well-known ports like DNS, and recommends five minutes or more.
  • Linux's connection tracking, which many home routers run, defaults to 30 seconds for a UDP flow that has only seen traffic one way, and 120 seconds once it has seen replies (nf_conntrack_udp_timeout and nf_conntrack_udp_timeout_stream).
  • Other NATs and firewalls pick their own values, sometimes well under two minutes.

So applications that need to stay reachable through a NAT send keep-alives: small packets whose only purpose is to refresh the mapping. RFC 8085 says they shouldn't be sent more than once every 15 seconds, and QUIC and WireGuard both have built-in options for them. The NAT article picks this thread up, including how two devices that are both behind NATs can reach each other directly using UDP (with STUN on port 3478, and "hole punching").

Building Reliability Yourself

Suppose you need your data to arrive, but TCP doesn't suit you. Then you have to build the missing pieces yourself, on top of UDP. Here's what that takes, piece by piece.

  1. Sequence numbers

    Put a counter in each message. Now the receiver can spot a gap (8 arrived, 7 didn't), a duplicate (a second 9), and reordering (5 after 6), and can hold early arrivals until the gap fills.

  2. Acknowledgements

    The receiver says "got 7" for each message. That's how the sender learns what arrived. ACKs travel over UDP too, so they can be lost as well; the receiver should ACK duplicates again, in case its first ACK was the one that went missing.

  3. Timers and retransmission

    If no ACK has come back after a while, the retransmission timeout (RTO), send the message again. Too short an RTO floods the network with needless copies; too long, and every loss costs a long stall. Getting it right means measuring the round trip time as you go.

In pseudocode, with a fixed RTO and one timer per message:

# --- sender ---
next_seq = 1
unacked = {}                         # seq -> (packet, time sent, tries)
def send(payload):
    global next_seq
    pkt = pack(next_seq, payload)
    sock.send(pkt)
    unacked[next_seq] = (pkt, now(), 1)
    next_seq += 1
def on_ack(seq):
    unacked.pop(seq, None)           # duplicate ACKs are harmless
def every_10_ms():
    for seq, (pkt, sent, tries) in list(unacked.items()):
        if now() - sent >= RTO:
            if tries == MAX_TRIES:
                del unacked[seq]; give_up(seq)   # tell the application
            else:
                sock.send(pkt)
                unacked[seq] = (pkt, now(), tries + 1)
# --- receiver ---
expected = 1
held = {}                            # early arrivals, waiting for a gap to fill
def on_datagram(pkt):
    global expected
    seq, payload = unpack(pkt)
    sock.send(pack_ack(seq))         # ACK every copy, even duplicates
    if seq < expected or seq in held:
        return                       # duplicate: drop it
    held[seq] = payload
    while expected in held:          # deliver everything now in order
        deliver(held.pop(expected))
        expected += 1

Watch it work in the simulator below. With the default settings, seed 28, the sender sends ten numbered datagrams 20 ms apart over a link with a 40 ms base delay, 0–30 ms of random jitter, a 10% chance of loss, a 10% chance of duplication, and a 10% chance of taking a 60 ms detour. Plain UDP delivers them in the order 1, 2, 3, 4, 6, 8, 5, 9, 10, 9: datagram 5 took the detour and arrives after 6 and 8, 9 arrives twice, and 7 never arrives at all. Nothing at the UDP level notices any of it.

Now switch on sequence numbers and ACKs with retransmission. The receiver drops the second 9, holds 6 until 5 arrives at 207 ms, then delivers 5 and 6 together. Datagram 7's timer (a 200 ms RTO) fires at 320 ms, the second copy arrives at 367 ms, and 7, 8, 9 and 10 are released at once. Everything arrives, in order, exactly once. But look at datagram 8: it reached the receiver at 180 ms and then sat in the buffer for over 180 ms, waiting for 7. That's head-of-line blocking, the price of ordering, and it's why a game or a voice call switches the ordering off and just skips 7.

The link

Reliability, built on top

Each datagram (times in ms)

Event log

Our little protocol already works, but it's missing a lot that TCP has:

  • A proper timer. A fixed 200 ms RTO is too slow on a LAN and far too fast on a satellite link. TCP measures round trip times continuously and adapts.
  • Efficient ACKs. One ACK per datagram is a lot of packets. TCP's ACKs are cumulative ("everything up to here"), with selective ACKs for the gaps.
  • Flow control. Nothing stops our sender from overrunning a slow receiver's buffer. TCP's receive window does.
  • Congestion control. Most importantly, our sender never slows down. When the network is losing packets because it's overloaded, retransmitting faster makes it worse.
  • Connection setup and teardown, so both sides agree on starting sequence numbers and know when the conversation is over.

Each of those is a solved problem, and the solutions are subtle enough that you should reuse them rather than reinvent them: either TCP, or a well-tested QUIC library. The next two articles show how TCP does it.

Reflection and Amplification

UDP's lack of a handshake has one ugly consequence. With TCP, a server can't send much to an address until that address has completed the handshake, which proves it's real. With UDP, the server answers whatever source address the request claims to come from. And IP doesn't check source addresses.

So an attacker can send a small request with a forged source address, the victim's, to some public UDP server, and the server sends its reply to the victim. That's reflection: the attack seems to come from thousands of innocent servers. When the reply is much bigger than the request, it's also amplification. The US cybersecurity agency CISA's advisory (TA14-017A) lists measured amplification factors (reply bytes per request byte) for a long list of protocols, including:

Protocol Amplification factor
DNS 28 to 54
NTP 556.9
CharGEN 358.8
Memcached 10,000 to 51,000

In February 2018, attackers found that memcached caching servers left open to the Internet on UDP port 11211 could turn a tiny request into an enormous reply. On 28 February, GitHub was hit by a reflected memcached attack peaking at 1.35 Tbps. Memcached 1.5.6, released the day before, had already switched UDP off by default.

There's deliberately no attack demo on this page; the defences are the interesting part:

  • Stop forged source addresses at the edge. BCP 38 (RFC 2827, 2000) asks every network to drop packets leaving it whose source address doesn't belong to it. Our ISP can easily tell that a packet from our street claiming to be from someone else's network is forged. If every network did this, reflection would be impossible. Many still don't.
  • Don't run open UDP services you don't need. Most amplifiers are forgotten or misconfigured servers: open DNS resolvers, old NTP servers answering monitoring queries, memcached exposed to the Internet.
  • Rate-limit responses. Authoritative DNS servers implement Response Rate Limiting (RRL), which notices the same answer going to the same address over and over and stops sending it, or sends a tiny truncated reply that tells a real client to retry over TCP.
  • Design new protocols to be small until the peer is proven. QUIC's first packet from a client must be padded to at least 1200 bytes, and until a server has validated the client's address, it may send no more than three times what it has received. A forged request gets a reply no bigger than the request was, times three, at most.

Where to Go Next

  • TCP: everything UDP left out, done properly: the handshake, sequence numbers and cumulative ACKs, retransmission timers, flow control, and the byte stream.
  • Congestion Control: why a sender that never slows down is dangerous, and how TCP and QUIC share a network fairly.
  • DNS: the query we sent, decoded field by field, and how R1 found the answer.
  • DHCP: UDP broadcasts in action, from a laptop with no address at all.
  • NAT: mapping tables, timeouts and hole punching, for UDP and TCP.
  • Checksums & CRC (Error Correction): why the Internet checksum works and what it misses.

Key Takeaways

  • IP delivers host to host; the transport layer delivers program to program. UDP (RFC 768, August 1980, IP protocol 17) does that and almost nothing else.
  • Ports are 16 bits. IANA: system 0–1023, user 1024–49151, dynamic 49152–65535. Linux picks ephemeral ports from 32768–60999 by default; Windows and macOS from 49152–65535. UDP and TCP port spaces are separate.
  • The kernel demultiplexes each datagram to the most specific matching socket. A connected socket only accepts its one peer; random source ports and query IDs protect DNS from forged answers.
  • The header is 8 bytes: source port, destination port, length (header + data, at least 8) and checksum. The laptop's query: a3 7d 00 35 00 25 57 eb, then 29 bytes of DNS.
  • The checksum is the ones'-complement of the ones'-complement sum over a pseudo-header (addresses, protocol 17, UDP length), the header and the zero-padded data. A computed 0000 is sent as ffff. Optional in IPv4 (0 = none), mandatory in IPv6 except for tunnels (RFC 6935/6936).
  • UDP has no connection, ordering, retransmission, duplicate suppression, flow control or congestion control. That suits DNS (one round trip), DHCP (no address yet), voice and games (late = lost, no head-of-line blocking), tunnels, and QUIC (RFC 9000), which builds its own reliability in user space.
  • UDP preserves message boundaries: one send is one receive, and a too-small receive buffer truncates the datagram.
  • Maximum payload: 65,507 bytes over IPv4, 65,527 over IPv6. But only 1472 (IPv4) or 1452 (IPv6) fit a 1500-byte MTU without fragmentation, and losing any fragment loses the whole datagram. DNS defaults to 1232-byte answers; QUIC needs 1200-byte datagrams.
  • A datagram to a closed port draws an ICMP port unreachable (connected sockets see ECONNREFUSED), but firewalls and rate limits often mean silence.
  • Of the two transports, only UDP can broadcast and multicast: DHCP, mDNS, RIP, SSDP.
  • NATs and firewalls track UDP by timeout: RFC 4787 asks for at least 2 minutes (5 recommended); Linux conntrack defaults to 30 s, or 120 s once replies are seen. Apps keep mappings alive with keep-alives no more than every 15 s.
  • Reliability on top of UDP needs sequence numbers, ACKs and retransmission timers, and ordering brings head-of-line blocking. Spoofable sources make UDP services reflectors and amplifiers; the defences are BCP 38, closing open services, response rate limiting, and QUIC-style anti-amplification limits.

UDP gets a message to the right program and stops there. Our homemade reliability layer got all ten datagrams through, but with a fixed timer, an ACK for every packet and no idea how fast it was allowed to send. Doing all of that properly, for a stream of bytes rather than a handful of messages, is a much bigger job. That's TCP.