UDP

Created · Updated

UDP (User Datagram Protocol) adds two things to IP: ports, which name a process’s socket on each host, and a checksum over the data. Each send() becomes one datagram, and each recv() returns one datagram. UDP adds no connection, numbering, acknowledgments, or retransmission. A lost datagram is gone, and datagrams arrive in whatever order the network delivers them. The alternative, TCP, provides those guarantees and pays for them in state and in waiting.

The mental model: UDP is IP with ports. The kernel keeps no state about the peer, so anything beyond delivering one datagram, such as order, retries, or pacing, is up to the program.

The UDP header, 32 bits to a row, with the values from a captured datagram. Byte 0: source port, 16 bits, value 40000; destination port, 16 bits, 9000. Byte 4: length, 16 bits, 11, the header and the data; checksum, 16 bits, 0x5457. Byte 8: data, 3 bytes, one.

The lab is four Alpine containers on Linux 6.12. client is at 10.70.1.10 and fd70:1::10, and server is at 10.70.2.20 and fd70:2::20. router connects their two networks, and other, at 10.70.2.30, shares the server’s network. Checksum offload is turned off, so the kernel computes and checks every checksum itself. Small Python programs and a Go 1.24 program sent and received datagrams. tcpdump captured them, tc netem added loss and delay, and /proc/net/snmp gave the kernel’s counters.

UDP and TCP

TCPUDP
Described asConnection-orientedConnectionless
Unit of dataA stream of bytesA datagram, one per send()
Kinds of socketA listening socket, which accepts connections and carries no data, and a connected socket for each peerOne kind, bound to a port, which receives from any sender
Before the first dataA three-way handshake creates a connectionNothing; the first datagram carries data
State in the kernelA connection with each peer: sequence numbers, windows, timersA socket and its receive queue, nothing per peer
A lost packetRetransmittedGone; the program sees a gap
OrderRestoredAs the datagrams arrive
DuplicatesDiscardedDelivered
A full receive bufferThe window closes, and the sender waitsNew datagrams are dropped
Congestion controlBuilt inNone
Header20 to 60 bytes8 bytes
Broadcast and multicastNo; a connection has two endsYes
  • A connection is the state both TCP ends keep for one pair of addresses and ports. A handshake creates it, and a FIN or RST ends it. RFC 9293 calls TCP connection-oriented. RFC 768 calls UDP transaction oriented, with no guarantee of delivery or against duplicates.
  • A session is a different thing at another layer: a TLS session, which can be resumed on a new connection, or a login that lasts across many connections. The OSI model’s session layer sits above transport. TCP has connections, not sessions.

The kernel and the program

StepDone by
Add the ports, length, and checksum, and build the IP headerKernel, on each send()
Pick a source port for a socket that has noneKernel, from ip_local_port_range
Check the checksum, find the socket by port, and queue the datagramReceiving kernel
Drop a datagram with a bad checksum, no socket, or no roomReceiving kernel, counted in /proc/net/snmp
Answer a datagram that has no socket with ICMP port unreachableReceiving kernel
Number messages, notice loss, resend, reorder, and paceProgram, or a protocol library it uses

The header

  • Source port: the sender’s port, where replies go. RFC 768 allows 0 when no reply is expected.
  • Destination port: the receiving socket’s port. The receiving kernel delivers the datagram to the socket bound to it.
  • Length: the header and data in bytes, at least 8. The captured datagram carried 3 bytes, one, so its length was 11.
  • Checksum: a ones’ complement sum over the header, the data, and a pseudo-header. The pseudo-header holds the source and destination addresses, the protocol number 17, and the UDP length. It isn’t sent; it ties the datagram to its addresses, so a datagram that reaches the wrong host fails the check.

Hand-built datagrams, sent from a raw socket, tested the checksum rules:

DatagramResult at the server
IPv4, checksum 0Delivered; tcpdump showed [no cksum]
IPv4, checksum 0x1234 instead of 0x2cd9Dropped; InCsumErrors and InErrors each rose by 1
IPv6, checksum 0Dropped; Udp6InCsumErrors rose by 1
  • In IPv4, a checksum of 0 means the sender computed none. IPv6 has no header checksum, so RFC 8200 makes the UDP checksum mandatory, apart from some tunnel protocols.

Datagrams keep their boundaries

The client sent one, two, three, and an empty datagram from port 40000. The server read them 2 seconds later:

recv()Returned
1one, 3 bytes
2two, 3 bytes
3three, 5 bytes
40 bytes, from 10.70.1.10:40000
  • The same three writes over TCP, read after 1 second, came back from one recv() as onetwothree. TCP carries bytes, not messages, so a TCP program marks where each message ends, such as with a length prefix.
  • An empty UDP datagram is a real datagram: send() returned 0, and the server received it. On a TCP socket, a recv() of 0 bytes means the peer has closed.
  • A datagram larger than the read buffer is cut. A 100-byte datagram read into 10 bytes returned 10 bytes with the MSG_TRUNC flag set, and the other 90 bytes were discarded. The next recv() returned the next datagram.
  • On Linux, recv() with MSG_TRUNC passed in returns the datagram’s real length, 100, instead of the number of bytes copied.

Loss, duplicates, and reordering

The router’s link to the server had tc netem set to delay 10 ms, lose 5%, duplicate 1%, and reorder 10% of packets. The client sent 1,000 messages of 100 bytes, one every 2 ms, each holding its number and the time it was sent. They went once as UDP datagrams and once over a TCP connection with TCP_NODELAY. With the delay alone, both delivered all 1,000 in order, the slowest in 10.6 ms over UDP and 10.5 ms over TCP. With loss, duplicates, and reordering added:

UDPTCP
Messages received939 of 1,000, plus 9 duplicates1,000, in order
Arrived after a higher-numbered one990
Median latency10.0 ms12.1 ms
99th-percentile latency10.1 ms231.8 ms
Messages later than 20 ms0216
  • UDP delivered exactly what the network did: gaps, duplicates, and swaps, each on time.
  • TCP hid every loss, but a lost segment held back every byte after it until its retransmission arrived: 216 messages were more than 20 ms late, and the slowest took 245.8 ms. This is head-of-line blocking: one loss delays every later message, even those that already arrived.
  • A program on UDP that needs order and reliability numbers its messages and resends lost ones itself. QUIC does this per stream, so a loss in one stream doesn’t delay the others.

The receive buffer

  • The kernel queues each arriving datagram on its socket’s receive buffer until the program reads it. The buffer’s size is SO_RCVBUF, by default net.core.rmem_default, 212,992 bytes.
  • UDP has no window, so the sender learns nothing about a full buffer. New datagrams are dropped, and only the receiver’s counters show it.

The client sent 10,000 datagrams of 1,000 bytes as fast as it could, while the server’s program slept for 4 seconds:

Server’s SO_RCVBUFEvery sendto() succeededDatagrams queuedDroppedRcvbufErrors
212,992, the defaultYes939,907+9,907
425,984, after asking for 1,000,000Yes1859,815+9,815
  • Each 1,000-byte datagram took 2,304 bytes of buffer. The kernel charges a datagram’s whole memory, including its packet structure, so small datagrams fill a buffer much sooner than their sizes add up to.
  • The kernel doubles a requested size for this overhead and caps the request at net.core.rmem_max, 212,992, so asking for 1,000,000 bytes gave 425,984. SO_RCVBUFFORCE, which needs CAP_NET_ADMIN, ignores the cap: 1,000,000 gave 2,000,000.
  • ss -uanm showed the queue, Recv-Q 214272, and the socket’s own drop count, d9907.

The send side

The client’s own outgoing queue can drop datagrams too. With its interface limited by tc netem to 10 Mbit/s and a queue of 100 packets, the same 10,000 datagrams gave:

  • Every sendto() returned 1,000, as if each datagram had been sent.
  • The queue dropped 9,892, and 108 reached the server. The client’s SndbufErrors counter rose by 9,892.
  • With the IP_RECVERR socket option set, the same run reported the drops: 9,881 calls failed with ENOBUFS, and 113 succeeded. 6 calls failed with ECONNREFUSED, because nothing listened on the server’s port and its port unreachable messages reached the socket.
  • Nothing slows a UDP sender down. A sender that sends faster than the path can carry loses the difference, and RFC 8085 asks protocols on UDP to add their own congestion control.

One kind of socket

  • TCP has two kinds of socket. A listening socket only accepts new connections, and each accepted or dialed connection gets its own socket that carries data to one peer.
  • UDP has one kind. Every UDP socket is bound to a local port, and the kernel puts any datagram that arrives for that port on its queue, whoever sent it.
  • A client’s socket is the same kind of thing as a server’s. The server’s port is known in advance; the client’s is picked by the kernel, but any host that learns it can send to it.
  • On an unconnected socket, recvfrom() returns each datagram with its sender’s address, and only the program can tell a reply from a stranger’s datagram. The unconnected socket on port 9031, below, received the datagram from other exactly as it received the client’s.

connect() on a UDP socket

  • connect() on a UDP socket sends nothing. On the server it returned in 7 µs, and the capture showed no packet. It records a default peer in the socket, and if the socket had no port, it picks one: an unbound client socket got 10.70.1.10:54234.
  • After connect(), send() needs no address, and the socket accepts datagrams only from that peer.
  • The server had a socket on port 9030 connected to the client’s port 40001 and an unconnected socket on port 9031. The client and other each sent a datagram to both ports:
SenderPort 9030, connectedPort 9031, unconnected
Client, 10.70.1.10:40001ReceivedReceived
other, 10.70.2.30Not received; the server’s kernel answered with ICMP port unreachableReceived

A connected socket also learns of errors from its peer. A dialed Go socket sent to port 9059, where nothing listened:

CallReturnedWhy
DialNo errorconnect() sends nothing, so there’s nothing to refuse
First WriteNo errorThe datagram left; the server’s kernel answered with ICMP port unreachable a moment later
Second Writeconnection refusedThe kernel had matched the ICMP error to the socket and stored ECONNREFUSED; the next call reported it
  • The error belongs to an earlier datagram, so it comes back from the call after the one that caused it. The next Read reports it the same way. It’s reported once and then cleared, so a third call can succeed, as the ICMP page shows.
  • An unconnected socket gets no such error by default: Linux passes ICMP errors only to connected sockets unless the program sets IP_RECVERR. With it set, the send-side test’s unconnected socket got ECONNREFUSED 6 times.
  • ss -uan listed the connected socket as ESTAB and the unconnected one as UNCONN. ESTAB here means only that the socket has a default peer. The peer’s kernel knows nothing about it, and no connection exists.
  • A NAT router or firewall on the path tracks UDP flows by addresses and ports and forgets them after an idle timeout, as the NAT page shows. That state belongs to the device, not to UDP.

Size

LimitBytes of dataWhy
Largest IPv4 datagram65,507IPv4’s 16-bit total length, minus 20 for IP and 8 for UDP
Largest IPv6 datagram65,527IPv6’s 16-bit payload length, minus 8 for UDP
Fits one packet on a 1,500-byte MTU, IPv41,4721,500 minus 20 for IP and 8 for UDP
  • A sendto() of 65,508 bytes over IPv4 failed with EMSGSIZE, and so did 65,528 over IPv6.
  • A 65,507-byte datagram left the client as 45 IP fragments, and only the first carried the UDP header. Losing any fragment loses the whole datagram. IP covers fragmentation.
  • With IP_MTU_DISCOVER set to IP_PMTUDISC_DO, which sets DF and forbids fragmenting, 1,472 bytes were sent and 1,473 failed with EMSGSIZE. IP_MTU on a connected socket reported the path MTU, 1,500.
  • DNS clients advertise a buffer of 1,232 bytes, a size chosen so answers fit in one packet without fragmentation.

Broadcast and multicast

  • A datagram can go to many hosts at once, because UDP needs no reply. A TCP connection always has exactly two ends.
  • A sendto() to the client’s broadcast address, 10.70.1.255, failed with EACCES until the socket set SO_BROADCAST. Then the router, on the same network, received it. The server, on the other network, didn’t: the router doesn’t forward broadcasts.
  • DHCP uses broadcast because a host asking for an address doesn’t have one yet. Multicast goes to a group of hosts that joined it, such as mDNS on 224.0.0.251, covered on the DNS page.

Built on UDP

ProtocolPortWhat it adds
DNS53A query ID that matches each answer to its query; the client retries after a timeout, and retries over TCP when an answer is truncated
DHCP67, 68A transaction ID; broadcast for a host with no address
NTP123Timestamps in each request and reply, to estimate the clock offset and delay
RTPChosen per callA sequence number and timestamp, so a media player notices loss and plays on time; a late packet is skipped, not resent
QUIC443 for HTTP/3Connections named by connection IDs, streams, acknowledgments and retransmission, congestion control, and TLS 1.3
WireGuardSet in its configurationEncrypted IP packets between peers named by public keys; a peer that moves is found again from its next authenticated datagram
VXLAN4789Ethernet frames carried between hosts, each tagged with a 24-bit network ID; the source port is usually a hash of the inner frame, so routers spread flows across paths
  • QUIC is a connection-oriented protocol built in the program, on a UDP socket. NAT routers and firewalls pass UDP, while a new IP protocol number often can’t cross them, and a library can change faster than every kernel. In Go, quic-go is such a library.

In a program

In Go:

  • net.ListenUDP("udp", &net.UDPAddr{Port: 9050}) opened an unconnected socket on [::]:9050, which accepts IPv4 and IPv6. ReadFromUDP returns one datagram and the sender’s address, and WriteToUDP sends to any address.
  • net.DialUDP calls connect(): no packet is sent, and LocalAddr() already showed 10.70.1.10:34618.
  • “Listen” in net.ListenPacket and net.ListenUDP means only binding a port; it isn’t TCP’s listening socket. net.ListenPacket("udp", "127.0.0.1:0") gives a client socket on a port the kernel picks, and it receives from anyone, like a server’s.
  • A socket that talks to one peer, such as a DNS client, gets the kernel’s sender check and ICMP errors from Dial. A socket that talks to many peers, such as a server or a client querying several servers at once, comes from ListenPacket, and the program compares each sender’s address itself.
  • ReadFromUDP into a 10-byte buffer returned 10 and no error for a 100-byte datagram: the truncation was silent. ReadMsgUDP returns the flags, and MSG_TRUNC was set.
  • On a dialed socket to a port with no listener, the first Write returned no error and the second returned connection refused, as the connect() section explains. A socket from ListenPacket never sees that error.
  • A Write of 70,000 bytes returned message too long.
  • SetReadBuffer(4 << 20) returned no error, but SO_RCVBUF became 425,984: the kernel’s cap applied without a word.
  • SetReadDeadline makes a read return a timeout error, the program’s own timer for resending a request that got no answer.

TCP covers retransmission and flow control, Keepalive covers keeping NAT state alive, and ICMP covers the errors a UDP socket receives.

References: RFC 768: User Datagram Protocol, RFC 8085: UDP usage guidelines, RFC 8200: IPv6, upper-layer checksums, RFC 9293: Transmission Control Protocol, udp(7), socket(7), ip(7), recv(2), tc-netem(8), RFC 1035: DNS, RFC 2131: DHCP, RFC 5905: NTP, RFC 3550: RTP, RFC 9000: QUIC, WireGuard, RFC 7348: VXLAN, Go net package, quic-go