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 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
| TCP | UDP | |
|---|---|---|
| Described as | Connection-oriented | Connectionless |
| Unit of data | A stream of bytes | A datagram, one per send() |
| Kinds of socket | A listening socket, which accepts connections and carries no data, and a connected socket for each peer | One kind, bound to a port, which receives from any sender |
| Before the first data | A three-way handshake creates a connection | Nothing; the first datagram carries data |
| State in the kernel | A connection with each peer: sequence numbers, windows, timers | A socket and its receive queue, nothing per peer |
| A lost packet | Retransmitted | Gone; the program sees a gap |
| Order | Restored | As the datagrams arrive |
| Duplicates | Discarded | Delivered |
| A full receive buffer | The window closes, and the sender waits | New datagrams are dropped |
| Congestion control | Built in | None |
| Header | 20 to 60 bytes | 8 bytes |
| Broadcast and multicast | No; a connection has two ends | Yes |
- 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
| Step | Done by |
|---|---|
| Add the ports, length, and checksum, and build the IP header | Kernel, on each send() |
| Pick a source port for a socket that has none | Kernel, from ip_local_port_range |
| Check the checksum, find the socket by port, and queue the datagram | Receiving kernel |
| Drop a datagram with a bad checksum, no socket, or no room | Receiving kernel, counted in /proc/net/snmp |
| Answer a datagram that has no socket with ICMP port unreachable | Receiving kernel |
| Number messages, notice loss, resend, reorder, and pace | Program, 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:
| Datagram | Result at the server |
|---|---|
| IPv4, checksum 0 | Delivered; tcpdump showed [no cksum] |
| IPv4, checksum 0x1234 instead of 0x2cd9 | Dropped; InCsumErrors and InErrors each rose by 1 |
| IPv6, checksum 0 | Dropped; 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 |
|---|---|
| 1 | one, 3 bytes |
| 2 | two, 3 bytes |
| 3 | three, 5 bytes |
| 4 | 0 bytes, from 10.70.1.10:40000 |
- The same three writes over TCP, read after 1 second, came back from one
recv()asonetwothree. 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, arecv()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_TRUNCflag set, and the other 90 bytes were discarded. The nextrecv()returned the next datagram. - On Linux,
recv()withMSG_TRUNCpassed 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:
| UDP | TCP | |
|---|---|---|
| Messages received | 939 of 1,000, plus 9 duplicates | 1,000, in order |
| Arrived after a higher-numbered one | 99 | 0 |
| Median latency | 10.0 ms | 12.1 ms |
| 99th-percentile latency | 10.1 ms | 231.8 ms |
| Messages later than 20 ms | 0 | 216 |
- 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 defaultnet.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_RCVBUF | Every sendto() succeeded | Datagrams queued | Dropped | RcvbufErrors |
|---|---|---|---|---|
| 212,992, the default | Yes | 93 | 9,907 | +9,907 |
| 425,984, after asking for 1,000,000 | Yes | 185 | 9,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 needsCAP_NET_ADMIN, ignores the cap: 1,000,000 gave 2,000,000. ss -uanmshowed 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
SndbufErrorscounter rose by 9,892. - With the
IP_RECVERRsocket option set, the same run reported the drops: 9,881 calls failed withENOBUFS, and 113 succeeded. 6 calls failed withECONNREFUSED, 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 fromotherexactly 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 got10.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
othereach sent a datagram to both ports:
| Sender | Port 9030, connected | Port 9031, unconnected |
|---|---|---|
| Client, 10.70.1.10:40001 | Received | Received |
other, 10.70.2.30 | Not received; the server’s kernel answered with ICMP port unreachable | Received |
A connected socket also learns of errors from its peer. A dialed Go socket sent to port 9059, where nothing listened:
| Call | Returned | Why |
|---|---|---|
Dial | No error | connect() sends nothing, so there’s nothing to refuse |
First Write | No error | The datagram left; the server’s kernel answered with ICMP port unreachable a moment later |
Second Write | connection refused | The 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
Readreports 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 gotECONNREFUSED6 times. ss -uanlisted the connected socket asESTABand the unconnected one asUNCONN.ESTABhere 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
| Limit | Bytes of data | Why |
|---|---|---|
| Largest IPv4 datagram | 65,507 | IPv4’s 16-bit total length, minus 20 for IP and 8 for UDP |
| Largest IPv6 datagram | 65,527 | IPv6’s 16-bit payload length, minus 8 for UDP |
| Fits one packet on a 1,500-byte MTU, IPv4 | 1,472 | 1,500 minus 20 for IP and 8 for UDP |
- A
sendto()of 65,508 bytes over IPv4 failed withEMSGSIZE, 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_DISCOVERset toIP_PMTUDISC_DO, which sets DF and forbids fragmenting, 1,472 bytes were sent and 1,473 failed withEMSGSIZE.IP_MTUon 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 withEACCESuntil the socket setSO_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
| Protocol | Port | What it adds |
|---|---|---|
| DNS | 53 | A query ID that matches each answer to its query; the client retries after a timeout, and retries over TCP when an answer is truncated |
| DHCP | 67, 68 | A transaction ID; broadcast for a host with no address |
| NTP | 123 | Timestamps in each request and reply, to estimate the clock offset and delay |
| RTP | Chosen per call | A sequence number and timestamp, so a media player notices loss and plays on time; a late packet is skipped, not resent |
| QUIC | 443 for HTTP/3 | Connections named by connection IDs, streams, acknowledgments and retransmission, congestion control, and TLS 1.3 |
| WireGuard | Set in its configuration | Encrypted IP packets between peers named by public keys; a peer that moves is found again from its next authenticated datagram |
| VXLAN | 4789 | Ethernet 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-gois 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.ReadFromUDPreturns one datagram and the sender’s address, andWriteToUDPsends to any address.net.DialUDPcallsconnect(): no packet is sent, andLocalAddr()already showed10.70.1.10:34618.- “Listen” in
net.ListenPacketandnet.ListenUDPmeans 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 fromListenPacket, and the program compares each sender’s address itself. ReadFromUDPinto a 10-byte buffer returned 10 and no error for a 100-byte datagram: the truncation was silent.ReadMsgUDPreturns the flags, andMSG_TRUNCwas set.- On a dialed socket to a port with no listener, the first
Writereturned no error and the second returnedconnection refused, as theconnect()section explains. A socket fromListenPacketnever sees that error. - A
Writeof 70,000 bytes returnedmessage too long. SetReadBuffer(4 << 20)returned no error, butSO_RCVBUFbecame 425,984: the kernel’s cap applied without a word.SetReadDeadlinemakes 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