TExcelTAD

UDP

UDP (User Datagram Protocol, RFC 768) is the simplest transport protocol. It adds just port numbers and a checksum to IP, and sends each message as an independent datagram. There is no connection, no acknowledgement, no retransmission and no ordering. If you need any of those, your application has to provide them.

That sounds like a weakness, but it's exactly what some applications want: DNS lookups, voice and video calls, online games, DHCP, NTP and QUIC (HTTP/3) all run over UDP.

TCP vs UDP

UDP TCP
Connection setup none 3-way handshake
Delivery best effort: may be lost, duplicated, reordered reliable, in order
Message boundaries preserved (one send = one datagram) none: a byte stream
Header 8 bytes 20–60 bytes
Flow / congestion control none yes
Broadcast / multicast yes no

The 8-byte header

text
| Source port (16) | Destination port (16) |
| Length (16)      | Checksum (16)         |
| Data ...                                 |

The length covers header + data. The checksum is computed over a pseudo-header (source IP, destination IP, protocol number and UDP length) plus the UDP header and data. Including the IP addresses means a datagram delivered to the wrong host is detected.

python · try it yourself
import socket
import struct

def checksum(data):
    if len(data) % 2:
        data += b"\0"
    total = sum(struct.unpack(f"!{len(data) // 2}H", data))
    while total >> 16:
        total = (total & 0xFFFF) + (total >> 16)
    return ~total & 0xFFFF

def udp_datagram(src_ip, dst_ip, sport, dport, payload):
    length = 8 + len(payload)
    pseudo = struct.pack("!4s4sBBH", socket.inet_aton(src_ip), socket.inet_aton(dst_ip),
                         0, socket.IPPROTO_UDP, length)
    header = struct.pack("!HHHH", sport, dport, length, 0)
    csum = checksum(pseudo + header + payload) or 0xFFFF   # 0 means "no checksum", so send FFFF
    return struct.pack("!HHHH", sport, dport, length, csum) + payload

dgram = udp_datagram("192.168.1.20", "192.168.1.1", 40001, 9999, b"temperature=21.5")
print(len(dgram), "bytes:", dgram.hex(" "))
sport, dport, length, csum = struct.unpack("!HHHH", dgram[:8])
print(f"{sport} -> {dport}, length {length}, checksum 0x{csum:04x}, data {dgram[8:]!r}")
24 bytes: 9c 41 27 0f 00 18 d5 34 74 65 6d 70 65 72 61 74 75 72 65 3d 32 31 2e 35
40001 -> 9999, length 24, checksum 0xd534, data b'temperature=21.5'

Datagrams keep their boundaries

With UDP, each sendto() produces exactly one datagram and each recvfrom() returns exactly one. TCP is a byte stream: three send() calls might arrive as one recv() or as five. Here is a model of the difference:

python · try it yourself
messages = [b"MOVE e2e4", b"MOVE e7e5", b"CHAT gg"]

# UDP: every message stays separate (it might be lost or reordered, but never merged).
udp_received = list(messages)
print("UDP recvfrom() calls:", udp_received)

# TCP: the receiver sees one continuous stream, cut wherever the network happened to cut it.
stream = b"".join(messages)
cuts = [6, 20]                         # where this particular run's recv() calls split it
pieces = [stream[a:b] for a, b in zip([0] + cuts, cuts + [len(stream)])]
print("TCP recv() calls:    ", pieces)
UDP recvfrom() calls: [b'MOVE e2e4', b'MOVE e7e5', b'CHAT gg']
TCP recv() calls:     [b'MOVE e', b'2e4MOVE e7e5CH', b'AT gg']

That's why protocols over TCP need framing (a length prefix or a delimiter like \r\n), while UDP applications get message boundaries for free.

Coping with loss: a request/retry pattern

UDP applications that need a reply usually resend after a timeout, like a DNS resolver does. Here's a deterministic simulation of a client over a link that drops some packets:

python · try it yourself
drop_pattern = iter([True, True, False, False, True, False])   # True = this datagram is lost

def send_over_lossy_link(payload):
    return None if next(drop_pattern) else b"ANSWER to " + payload

def query(payload, retries=3, timeout_ms=500):
    for attempt in range(1, retries + 1):
        reply = send_over_lossy_link(payload)
        if reply:
            print(f"  attempt {attempt}: got {reply.decode()!r}")
            return reply
        print(f"  attempt {attempt}: no reply after {timeout_ms} ms, retrying")
        timeout_ms *= 2                  # exponential back-off
    print("  giving up")

for q in [b"query-1", b"query-2", b"query-3"]:
    print(q.decode())
    query(q)
query-1
  attempt 1: no reply after 500 ms, retrying
  attempt 2: no reply after 1000 ms, retrying
  attempt 3: got 'ANSWER to query-1'
query-2
  attempt 1: got 'ANSWER to query-2'
query-3
  attempt 1: no reply after 500 ms, retrying
  attempt 2: got 'ANSWER to query-3'

Because the client might retry a request whose reply was lost, the server may see the same request twice. Good UDP protocols make requests idempotent (safe to repeat) or tag them with an ID so duplicates can be ignored.

Real UDP sockets

The real code is short, because there's no connection to manage. This won't run in the browser, so it's shown as a plain listing:

python
import socket

# Server
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("0.0.0.0", 9999))
while True:
    data, addr = sock.recvfrom(2048)       # one datagram, and who sent it
    sock.sendto(b"ACK " + data, addr)

# Client (in another program)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1.0)
sock.sendto(b"temperature=21.5", ("192.168.1.1", 9999))
print(sock.recvfrom(2048))

You can poke at UDP services from a terminal with netcat:

bash
echo -n "hello" | nc -u -w1 192.168.1.1 9999

Sample output:

text
ACK hello

Tip: Keep UDP payloads under about 1200 bytes when sending across the Internet. A datagram larger than the path MTU gets fragmented by IP, and losing any fragment loses the whole datagram.

Go further: UDP and Amplification Attacks measures the amplification factor in a sample capture.

Test yourself

How big is the UDP header?

  1. 4 bytes
  2. 8 bytes
  3. 20 bytes
  4. 40 bytes

Which is true of UDP?

  1. It retransmits lost datagrams
  2. It guarantees ordering
  3. It preserves message boundaries
  4. It needs a handshake

Why does the UDP checksum include a pseudo-header with the IP addresses?

  1. To encrypt the addresses
  2. To detect datagrams delivered to the wrong host or with a corrupted address
  3. To make the header longer
  4. Routers require it