Sub topic 3
UDP: a minimal transport service
This chapter assumes you know the four-layer model and encapsulation, and that you have met the socket call sequence from the previous chapter. It also assumes you can read hexadecimal numbers. UDP (User Datagram Protocol) is the simplest transport protocol you will meet in GATE. Knowing exactly what it leaves out makes TCP's extra machinery easier to understand.
What UDP provides
The network layer (IP) delivers packets between hosts on a best-effort basis. It can lose, duplicate, delay, or reorder them. The transport layer extends this host-to-host delivery to process-to-process delivery. UDP adds only two things on top of IP:
- Multiplexing and demultiplexing by port. Many processes on one host can send and receive at the same time.
- An optional error check. A checksum detects corruption in the header and data.
UDP does not provide:
- connection setup (no handshake)
- reliable delivery (no acknowledgements, no retransmission)
- ordering
- flow control
- congestion control
Each UDP send is a self-contained datagram. UDP preserves message boundaries. If a sender calls sendto twice, the receiver needs two recvfrom calls and gets two separate messages. TCP, in contrast, delivers a byte stream with no message boundaries.
| Property | UDP | TCP |
|---|---|---|
| Connection setup | None | Three-way handshake |
| Unit of data | Datagram (boundaries kept) | Byte stream |
| Reliability and ordering | No | Yes |
| Flow and congestion control | No | Yes |
| Header size | 8 bytes, fixed | 20 to 60 bytes |
| Socket type | `SOCK_DGRAM` | `SOCK_STREAM` |
The UDP header
The header is always 8 bytes, made of four 16-bit fields.
- Source port. This identifies the sending process. A client usually gets an ephemeral port from the operating system. A UDP sender that never expects a reply may set it to 0.
- Destination port. This identifies the receiving process. Well-known examples are 53 (DNS), 67 and 68 (DHCP), and 161 (SNMP).
- Length. This is the size of the header plus the data, in bytes. The minimum is 8, which is a datagram with no data. The maximum is 65535.
- Checksum. This is a 16-bit error-detection value, described below.
The length field limits the payload. The largest UDP datagram is 65535 bytes. Inside an IPv4 packet, the 20-byte IP header and the 8-byte UDP header are subtracted from the IP total length limit of 65535. That leaves a maximum payload of 65535 − 20 − 8 = 65507 bytes.
Reading a header: a GATE-style example
A classic question gives a UDP header as hexadecimal bytes and asks for the ports and the data size. Take the header 06 32 00 0D 00 1C E2 17.
import struct
header = bytes.fromhex("0632000D001CE217")
src, dst, length, checksum = struct.unpack("!HHHH", header)
print("source port:", src) # 1586
print("destination port:", dst) # 13
print("length:", length) # 28
print("data bytes:", length - 8) # 20
print("checksum:", hex(checksum)) # 0xe217By hand:
- Source port: 0x0632 = 6×256 + 3×16 + 2 = 1586.
- Destination port: 0x000D = 13, the daytime service.
- Length: 0x001C = 28 bytes in total, so the data is 28 − 8 = 20 bytes.
The most common mistake is to report 28 as the data size. Always subtract the 8-byte header.
The checksum
The checksum covers more than the UDP datagram itself. The sender computes it over three things:
- A pseudo-header made of the source IP address, the destination IP address, a zero byte, the protocol number (17 for UDP), and the UDP length.
- The UDP header, with the checksum field set to 0.
- The data, padded with a zero byte if its length is odd.
The pseudo-header is not transmitted. Including it lets the receiver detect a datagram that was delivered to the wrong host or with a corrupted IP address, which an ordinary checksum over the UDP bytes would miss.
The arithmetic uses 16-bit words and one's complement addition:
- Add all 16-bit words. Whenever there is a carry out of bit 16, wrap it around and add it back at the bottom.
- Take the bitwise complement of the result. That is the checksum.
The receiver adds all the words, including the checksum. If nothing was corrupted, the sum is 0xFFFF.
Here is a two-word example. Add 0xE6E5 and 0xD6F3:
- 0xE6E5 + 0xD6F3 = 0x1BDD8. This produces a carry out of bit 16.
- Wrap the carry: 0xBDD8 + 1 = 0xBDD9.
- Complement: 0xFFFF − 0xBDD9 = 0x4226.
def ones_complement_sum(data: bytes) -> int:
if len(data) % 2:
data += b"\x00" # pad odd length with a zero byte
total = 0
for i in range(0, len(data), 2):
total += (data[i] << 8) | data[i + 1]
total = (total & 0xFFFF) + (total >> 16) # wrap the carry
return total
words = bytes.fromhex("E6E5D6F3")
checksum = ~ones_complement_sum(words) & 0xFFFF
print(hex(checksum)) # 0x4226
# Receiver check: data plus checksum must sum to 0xFFFF
print(hex(ones_complement_sum(words + checksum.to_bytes(2, "big")))) # 0xffffTwo rules to remember:
- In IPv4 the checksum is optional. A value of 0 means "no checksum computed". If the computed checksum happens to be 0, the sender transmits 0xFFFF instead, which is the same value in one's complement arithmetic. In IPv6 the checksum is mandatory.
- A checksum detects errors but never corrects them. A UDP receiver that finds a bad checksum silently discards the datagram.
Demultiplexing
When a host receives an IP packet whose protocol field is 17, it passes the UDP datagram to the socket bound to the destination port. A UDP socket is identified by the two-tuple (destination IP address, destination port). Datagrams from different senders to the same IP address and port all arrive at the same socket. The application learns the sender's address from recvfrom.
A TCP socket is identified by the four-tuple (source IP, source port, destination IP, destination port). Each client connection therefore gets its own socket on the server. This difference is a frequent conceptual question.
UDP with the socket API
The UDP calls are shorter than the TCP calls. There is no listen, no accept, and no connection. The server binds a port and then reads datagrams. The client sends with sendto.
Run the server in one terminal:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:
server.bind(("127.0.0.1", 5001))
print("listening on 127.0.0.1:5001")
while True:
data, addr = server.recvfrom(2048) # one call = one datagram
print("got", data, "from", addr)
server.sendto(data.upper(), addr) # reply to the sender's addressRun the client in another terminal:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
client.settimeout(2.0) # UDP never retransmits for you
client.sendto(b"hello", ("127.0.0.1", 5001))
client.sendto(b"world", ("127.0.0.1", 5001))
for _ in range(2):
try:
data, addr = client.recvfrom(2048)
print(data, addr) # b'HELLO', then b'WORLD'
except socket.timeout:
print("no reply: the datagram or its answer was lost")Note three behaviours:
- The two
sendtocalls produce two datagrams. The server'srecvfromreturns them one at a time, never merged. - The client has no
bind. The operating system assigns an ephemeral source port on the firstsendto. - If a datagram is lost, nothing happens automatically. The client sees only a timeout, so any retransmission logic belongs to the application. If
recvfromis given a buffer smaller than the datagram, the excess bytes are discarded.
When to choose UDP
UDP fits when low delay matters more than perfect delivery, or when the application wants to control reliability itself:
- Request and response over a short exchange. DNS queries are one small datagram each way. A TCP handshake would triple the round trips for a single lookup.
- Real-time media. In a voice call, a retransmitted packet arrives too late to be useful.
- Broadcast and multicast. Connection-oriented TCP cannot address many receivers at once.
- Building a custom protocol. QUIC, the transport under HTTP/3, runs over UDP and implements its own reliability and congestion control.
The cost of having no congestion control is real. A UDP sender can transmit as fast as it likes and crowd out TCP flows that back off. Many networks therefore rate-limit UDP traffic.
Common GATE patterns for UDP
- Header size is 8 bytes. Data size is length minus 8.
- Maximum payload over IPv4 is 65507 bytes.
- The checksum uses a pseudo-header and one's complement addition.
- UDP preserves message boundaries. TCP does not.
- UDP identifies a socket by two values, and TCP by four.
- DNS normally uses UDP port 53. TCP is used for zone transfers and for responses too large for UDP.
Exercise
A UDP header, in hexadecimal, is 1F 90 00 35 00 2A 8C 4E. (a) What are the source and destination ports? (b) How many bytes of data does the datagram carry? (c) Which well-known service is the destination port likely to be?
Show answer
(a) Source port 0x1F90 = 1×4096 + 15×256 + 9×16 + 0 = 8080. Destination port 0x0035 = 3×16 + 5 = 53. (b) The length 0x002A = 42 bytes in total, so the data is 42 − 8 = 34 bytes. (c) Port 53 is DNS.
Exercise
A sender calls sendto three times with payloads of 100, 200, and 50 bytes on a UDP socket. The receiver calls recvfrom with a 1024-byte buffer. How many calls are needed to read all the data, and what does each return? Contrast this with the same sends over a TCP connection.
Show answer
Three calls, returning 100, 200, and 50 bytes in that order, assuming no loss or reordering. UDP preserves each datagram as one message. Over TCP the 350 bytes form one stream, so a single recv with a 1024-byte buffer could return all 350 bytes, or the data could be split across several calls at arbitrary points.
Exercise
Compute the 16-bit one's complement checksum of the two words 0x8F3A and 0x71C6, and verify it as a receiver would.
Show answer
0x8F3A + 0x71C6 = 0x10100. Wrap the carry: 0x0100 + 1 = 0x0101. The complement is 0xFFFF − 0x0101 = 0xFEFE. The receiver adds 0x0101 + 0xFEFE = 0xFFFF, which confirms no error was detected.