Sub topic 4
UDP: independent datagrams with a minimal header
This chapter assumes you know the layered model and what ports are, and that you can read basic Python. It builds on the earlier chapters about the transport layer's role, sockets and multiplexing, and connectionless versus connection-oriented delivery. TCP is covered in later chapters.
The working model
UDP (User Datagram Protocol) adds two things to IP: port numbers and an optional integrity check. It adds nothing else. There is no handshake, no acknowledgment, no retransmission, no ordering, and no flow or congestion control.
Each call to sendto hands UDP one message. UDP wraps it in an 8-byte header and passes it to IP as one packet. The receiver's recvfrom returns that message whole, or doesn't return it at all. UDP never merges two messages and never splits one into two reads. A message that UDP delivers is called a datagram.
The header
The UDP header is four 16-bit fields, 8 bytes in total. TCP's header is at least 20 bytes.
| Field | Size | Meaning |
|---|---|---|
| Source port | 16 bits | The sender's port. Receivers use it as the reply address. |
| Destination port | 16 bits | Selects the receiving socket on the destination host. |
| Length | 16 bits | Header plus payload, in bytes. The minimum is 8. |
| Checksum | 16 bits | Detects corruption of the header, payload, and some IP fields. |
You can decode a header yourself with struct. The ! means network byte order (big-endian).
import struct
header = bytes.fromhex("1f90 0050 0010 abcd")
src, dst, length, checksum = struct.unpack("!HHHH", header)
print(src, dst, length, checksum, "payload bytes:", length - 8)This prints 8080 80 16 43981 payload bytes: 8.
Size limits
The length field is 16 bits, so a datagram can't exceed 65,535 bytes. IPv4 spends 20 bytes on its own header and UDP spends 8. That leaves a maximum payload of 65,507 bytes over IPv4.
A large datagram is a poor idea even when it is legal. Ethernet commonly has a 1500-byte MTU (maximum transmission unit). A datagram larger than the MTU makes IP fragment it. If any one fragment is lost, the receiver discards the whole datagram, and UDP never retransmits it. A common safe payload for IPv4 over Ethernet is 1472 bytes (1500 − 20 − 8). Many applications choose around 1200 bytes so the datagram also fits IPv6 paths and tunnels.
The checksum
The checksum covers the UDP header, the payload, and a "pseudo-header" taken from the IP header (source address, destination address, protocol). The pseudo-header lets the receiver detect a datagram that was delivered to the wrong host. In IPv4 the checksum is optional, and a value of 0 means "not computed". In IPv6 it is mandatory. A datagram that fails the check is silently dropped, and the application never learns it existed. The checksum algorithm is covered in the checksums chapter.
What UDP does not do
The next table shows what you must build yourself if your application needs these properties.
| Property | UDP provides it? | Consequence |
|---|---|---|
| Delivery | No | A datagram can vanish at a router, in a full queue, or at a full receive buffer. |
| Order | No | Datagram 2 can arrive before datagram 1. |
| No duplicates | No | A network fault can deliver the same datagram twice. |
| Message boundaries | Yes | One `sendto` is one `recvfrom`. |
| Integrity | Mostly | The checksum catches most corruption, but not all. |
| Sender slowdown | No | UDP sends as fast as the application asks. |
The last row matters for the network as a whole. A UDP sender that ignores congestion can crowd out TCP traffic. Applications sending large volumes over UDP need their own rate control.
Sockets with UDP
A UDP server creates a SOCK_DGRAM socket and binds it to a port. It has no listen or accept step. There is no connection to accept, so one socket handles every client.
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as srv:
srv.bind(("127.0.0.1", 9001))
print("listening on 127.0.0.1:9001")
while True:
data, addr = srv.recvfrom(2048)
print(f"{len(data)} bytes from {addr}")
srv.sendto(data, addr)recvfrom returns the payload and the sender's address. The server replies to that address. This is the only way it knows who sent the datagram, because no connection records it.
Start the server first, in its own process. Then run the client in another process:
import socket
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, server = cli.recvfrom(2048)
print(reply, server)
except socket.timeout:
print("no reply")The client never calls bind. The first sendto makes the operating system assign an unused ephemeral port, and the server sees that port as the client's address.
The timeout is required. If the request or the reply is lost, UDP reports nothing, and recvfrom would wait forever. Real programs typically resend after a timeout and give up after a few tries. They also tag requests with an ID so they can match replies and discard duplicates.
Message boundaries in practice
If a client sends b"hello " and then b"world", a UDP server's recvfrom calls return b"hello " and b"world" as two separate results. Over TCP the same two writes might arrive as one read. With UDP you never reassemble messages from fragments of a stream. You still must handle the cases of a missing, reordered, or duplicated message.
Common errors
The receive buffer is too small
recvfrom(n) reads at most n bytes of one datagram. If the datagram is longer, the rest is discarded. On Linux and macOS, no error is raised and you silently get a truncated message. On Windows, the call raises an error. Use a buffer at least as large as the biggest datagram your protocol allows. Using 65535 is always safe.
Treating an empty result as end of stream
Over TCP, recv returning b"" means the peer closed. Over UDP, b"" means someone sent a zero-length datagram, which is legal. UDP has no close signal, so a UDP server must define its own way to stop, such as a special message.
Replying to the wrong place
The server must answer to the addr returned by recvfrom. Sending to a fixed address breaks as soon as a second client appears. If the reply seems to vanish, check that the server's reply comes from the same IP and port the client sent to. A client using connect (below) discards datagrams from any other source.
Assuming a send means a receive
sendto returning means the datagram was handed to the local network stack. It says nothing about whether anyone received it. A send to a port nobody is listening on succeeds too.
Binding to the wrong address
Binding to 127.0.0.1 accepts only local traffic. To accept datagrams from other machines, bind to "0.0.0.0" (all IPv4 interfaces). Also check that a firewall isn't dropping the port, because UDP gives no error to point at it.
Dropped datagrams under load
The kernel keeps a limited receive buffer for each socket. If the application reads slowly and the buffer fills, new datagrams are discarded without notice. A server that gets bursts should read quickly, hand work to other threads or tasks, and consider a larger buffer with SO_RCVBUF.
Connected UDP sockets
You can call connect on a UDP socket. This sends no packets. It only stores the peer's address in the socket. You can then use send and recv instead of sendto and recvfrom. The socket also ignores datagrams from any other source.
A connected socket also reports some errors. When a datagram reaches a host with no listener, that host usually returns an ICMP "port unreachable" message. A connected socket turns it into an error on a later call. An unconnected socket can't tell which of its many destinations the message was about, so it ignores it.
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(2)
s.connect(("127.0.0.1", 9999)) # assumes nothing listens on this port
s.send(b"hello")
try:
s.recv(1024)
except ConnectionRefusedError:
print("ICMP port unreachable received")
except socket.timeout:
print("no reply and no error")On Linux this prints the first message when nothing is listening. Other systems can differ, and firewalls often drop the ICMP message, which leaves only the timeout. Treat the error as a useful hint and never rely on it.
Why use UDP at all
Because UDP adds so little, it suits cases where the application wants control over loss and timing. Examples are DNS queries (one small request, one small reply, easy to retry), live audio and video (a late packet is worthless), and games (the newest position replaces the old one). Protocols such as QUIC build their own reliability on top of UDP. The final chapter compares the two protocols in detail.
Exercise
A UDP server calls recvfrom(10) and a client sends a 25-byte datagram. On Linux, what does the server get, and how many bytes of that datagram can it read later?
Show answer
It gets the first 10 bytes, with no error. The remaining 15 bytes are discarded with the rest of the datagram, so it can't read them later. The next recvfrom starts with the next datagram. To avoid this, use a buffer at least as large as the biggest datagram, for example 65535.
Exercise
Your UDP client sends a request and waits with recvfrom and no timeout. Sometimes it hangs forever. Explain why and describe a fix.
Show answer
UDP doesn't detect or report lost datagrams. If the request or the reply is dropped, no data and no error ever arrive, so recvfrom blocks forever. Set a timeout with settimeout, catch socket.timeout, and resend the request a limited number of times. Include a request ID so duplicate or late replies can be recognized.
Exercise
A UDP header has the length field 0x0028. How many payload bytes does the datagram carry?
Show answer
0x0028 is 40 bytes. The length includes the 8-byte header, so the payload is 40 - 8 = 32 bytes.