Sub topic 4
UDP: Independent Datagrams with a Minimal Header
This chapter assumes you know what an IP address and a packet are, and that you have seen ports and sockets. It also assumes basic Python. It covers how UDP delivers data, what its header contains, and the mistakes people commonly make with it.
The working model
UDP (User Datagram Protocol) adds only two things to IP: port numbers and an optional checksum. It keeps no connection state. Each call to sendto produces one datagram, and the receiver's recvfrom returns that datagram whole or not at all.
Because nothing is set up in advance, there is no handshake. A sender can transmit the first byte immediately. The cost is that UDP gives no guarantees. A datagram can be lost, duplicated, or reordered, and neither side is told.
The UDP header
The header is 8 bytes, four fields of 16 bits each.
| Field | Size | Purpose |
|---|---|---|
| Source port | 16 bits | Port the sender used. The reply goes here. |
| Destination port | 16 bits | Selects the receiving socket. |
| Length | 16 bits | Header plus payload, in bytes. Minimum is 8. |
| Checksum | 16 bits | Detects corruption of the header and payload. |
The length field allows a maximum of 65,535 bytes. After the 20-byte IPv4 header and 8-byte UDP header, the largest payload is 65,507 bytes. In practice, keep payloads below the path MTU, roughly 1,200 to 1,472 bytes. A larger datagram is fragmented by IP, and losing one fragment loses the whole datagram.
Datagrams keep their boundaries
UDP preserves message boundaries. If the sender calls sendto twice, the receiver needs two recvfrom calls, and each returns exactly one message. This is the opposite of TCP, which delivers a byte stream.
If your receive buffer is smaller than the datagram, the extra bytes are discarded. They are not saved for the next call. Use a buffer at least as large as your largest expected message.
A worked example
This example is an echo exchange. The server waits for one datagram and sends it back. The client sets a timeout, because UDP never reports a lost datagram.
import socket
# Server (run in one process)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as srv:
srv.bind(("127.0.0.1", 9001))
data, addr = srv.recvfrom(2048)
srv.sendto(data, addr)
# Client (run in another process)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as cli:
cli.settimeout(2)
cli.sendto(b"ping", ("127.0.0.1", 9001))
try:
reply, _ = cli.recvfrom(2048)
print(reply)
except socket.timeout:
print("no reply")Notice what is missing. There is no listen, accept, or connect. The server learns the client's address from recvfrom and replies with sendto(data, addr). The client never calls bind, so the operating system assigns it an ephemeral source port on the first sendto.
Common errors
- Waiting forever. Without
settimeout,recvfromblocks indefinitely if the request or reply is lost. - Assuming delivery. A successful
sendtomeans the datagram was handed to the network stack. It does not mean the peer received it. - Assuming order. Two datagrams can arrive swapped. If order matters, add your own sequence number to the payload.
- Small receive buffers. A buffer of 1024 bytes silently truncates a 2000-byte datagram.
- Oversized datagrams. Payloads above the MTU risk fragmentation and higher loss.
- Ignoring the sender. Any host can send to your port. Check
addrif you expect a specific peer.
When you need reliability over UDP, the application must supply it: timeouts, retries, sequence numbers, and duplicate detection. Protocols such as DNS do this with a simple retry, and others, such as QUIC, build a full reliable transport on top of UDP.
Exercise
A client sends three datagrams of 100 bytes each to a UDP server that calls recvfrom(1024) three times. How many bytes does each call return, and what could differ from what the client sent?
Show answer
Each call returns 100 bytes, because UDP preserves datagram boundaries and does not merge them. The datagrams could arrive in a different order, or one could be missing, in which case the third call blocks until a timeout (if set). UDP does not detect or repair either problem.
Exercise
What is the largest UDP payload over IPv4, and why should you usually send much less?
Show answer
65,507 bytes (65,535 minus 20 for the IP header and 8 for the UDP header). Anything larger than the path MTU is fragmented by IP, and losing a single fragment causes the whole datagram to be dropped, so payloads of about 1,200 to 1,472 bytes are safer.