Sub topic 5
Checksums and error detection
This chapter explains how TCP and UDP detect corrupted data, how the Internet checksum is computed, and what each protocol does when a check fails. It assumes you know the layered network model, what an IP address and a packet are, and basic Python. The Python examples need no network access.
Why the transport layer checks for errors
IP is best-effort. It can drop, duplicate, reorder or deliver damaged packets. The link layer usually protects each hop with a strong check such as Ethernet's 32-bit CRC. That check covers only one link, though. A router can corrupt a packet in memory after the incoming frame passed its CRC and before the outgoing frame gets a new one. A buggy network card or a faulty memory module can do the same.
The transport layer therefore adds an end-to-end check. The sender computes a small value from the segment and stores it in the header. The receiver recomputes the value from what arrived. A mismatch means the data changed in transit.
A checksum is a detection mechanism. It cannot repair anything. What happens next depends on the protocol.
The Internet checksum
UDP, TCP and the IPv4 header all use the same algorithm, defined in RFC 1071. It is a 16-bit one's complement sum:
- Treat the data as a sequence of 16-bit big-endian words. If the length is odd, pad with one zero byte for the calculation only. The pad byte is not transmitted.
- Add the words as ordinary integers.
- While the sum has bits above bit 15, add those carry bits back into the low 16 bits. This is the "end-around carry".
- Invert every bit of the result. That is the checksum.
The sender computes the checksum with the checksum field set to zero. The receiver sums the whole segment, including the stored checksum. An undamaged segment sums to 0xFFFF. After inversion that is 0x0000, so the receiver only needs to test for zero.
The RFC gives a worked example. The bytes 00 01 f2 03 f4 f5 f6 f7 sum to 0xddf2 after folding carries. The checksum is therefore 0x220d.
import socket
import struct
def internet_checksum(data: bytes) -> int:
"""16-bit one's complement checksum (RFC 1071)."""
if len(data) % 2:
data += b"\x00"
total = 0
for i in range(0, len(data), 2):
total += (data[i] << 8) | data[i + 1]
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def udp_checksum_ipv4(src: str, dst: str, sport: int, dport: int, payload: bytes):
length = 8 + len(payload)
pseudo = (
socket.inet_aton(src)
+ socket.inet_aton(dst)
+ struct.pack("!BBH", 0, 17, length) # zero, protocol 17 = UDP, UDP length
)
header = struct.pack("!HHHH", sport, dport, length, 0) # checksum field = 0
csum = internet_checksum(pseudo + header + payload)
# In UDP, a transmitted value of 0 means "no checksum", so 0 is sent as 0xFFFF.
csum = csum or 0xFFFF
full_header = struct.pack("!HHHH", sport, dport, length, csum)
return csum, pseudo, full_header
# The example from RFC 1071
rfc = bytes.fromhex("0001f203f4f5f6f7")
print(hex(internet_checksum(rfc))) # 0x220d
# A UDP datagram: the receiver's check over everything, stored checksum included, gives 0
payload = b"ping"
csum, pseudo, header = udp_checksum_ipv4("10.0.0.1", "10.0.0.2", 50000, 9001, payload)
print(hex(csum), internet_checksum(pseudo + header + payload) == 0) # ... True
# A single flipped bit is detected
damaged = bytes([payload[0] ^ 0x01]) + payload[1:]
print(internet_checksum(pseudo + header + damaged) == 0) # False
# Reordering whole 16-bit words is NOT detected
print(internet_checksum(b"\x12\x34\x56\x78") == internet_checksum(b"\x56\x78\x12\x34")) # TrueThe last line shows a known weakness, covered below. The function also returns the same value on any machine, because it always reads words in network byte order.
What the checksum covers
The checksum does not cover only the transport header and payload. TCP and UDP also include a pseudo-header, which is a set of fields taken from the IP header. It is used for the calculation and is never transmitted as part of the segment.
For IPv4, the pseudo-header contains:
- the source IP address (4 bytes)
- the destination IP address (4 bytes)
- one zero byte
- the protocol number (6 for TCP, 17 for UDP)
- the transport-layer length in bytes (2 bytes)
The IPv6 version uses 16-byte addresses and a 32-bit length, but the idea is the same.
The reason is that the transport layer must catch a segment delivered to the wrong host or with the wrong protocol. Ports alone do not identify a destination. If a router damaged only the destination address in the IP header, a segment would reach the wrong machine with a payload that looks intact. The pseudo-header ties the segment to the addresses it was meant for. A receiver whose checksum includes its own address detects the mismatch.
This has a consequence for NAT. A device that rewrites an IP address or port must also adjust the transport checksum. NAT devices do this incrementally, as RFC 1624 describes, instead of summing the whole segment again.
| Protocol | Checksum field | Covers | Mandatory |
|---|---|---|---|
| IPv4 header | Header checksum | IPv4 header only | Yes |
| IPv6 header | None | Not applicable | Not applicable |
| UDP over IPv4 | 16 bits in UDP header | Pseudo-header, UDP header, payload | No, zero means unused |
| UDP over IPv6 | 16 bits in UDP header | Pseudo-header, UDP header, payload | Yes |
| TCP | 16 bits in TCP header | Pseudo-header, TCP header, payload | Yes |
IPv6 dropped its own header checksum. It relies on the link-layer CRC and the transport checksum, and this saves each router from recomputing a checksum after decrementing the hop limit. That is also why the UDP checksum became mandatory over IPv6.
What happens when the check fails
The receiving network stack discards a segment that fails verification. It does not deliver any bytes to the application. After that the two protocols differ.
- UDP drops the datagram. Nothing tells the sender, and the receiving application never sees an error. If the application needs the data, it must detect the gap itself, for example with a timeout or its own sequence numbers.
- TCP also drops the segment, and it does not acknowledge it. The sender's retransmission timer expires, or duplicate acknowledgments trigger a fast retransmit, and the segment is sent again. The next chapters cover that mechanism. For now, note that the checksum turns corruption into loss, and TCP already knows how to recover from loss.
A segment that fails verification is not sent back with an error message. A receiver cannot trust any header field in a corrupted segment, including the port numbers and the length, so it has no reliable way to say who should be told.
The UDP checksum is optional in IPv4
In IPv4, a UDP checksum field of zero means the sender did not compute a checksum. The receiver skips verification. This saved CPU time on old hardware. It is rarely a good idea now, because it gives up end-to-end detection and also protects less against misdelivery.
This rule creates a corner case. A computed checksum can legitimately come out as zero. To avoid confusion with "no checksum", the sender transmits 0xFFFF instead. The two values are the same in one's complement arithmetic, because negative zero is all ones. The code above does this with csum or 0xFFFF. TCP has no such rule, since its checksum is always present.
The same arithmetic is why the receiver's test is "sum equals all ones" rather than "sum equals the stored value". It does not need to know which representation of zero the sender chose.
Limits of a 16-bit checksum
The Internet checksum is cheap, but it is not strong. Know these gaps:
- Word reordering. Addition is commutative, so swapping two 16-bit words leaves the sum unchanged. The last line of the code example shows this.
- Compensating errors. Two errors can cancel out. If one word gains 1 and another loses 1, the sum is unchanged.
- Zero-filled data. Inserting or removing 16-bit words of zeros goes undetected.
- Weak coverage against burst errors. A CRC is designed to detect bursts of flipped bits. The Internet checksum is only about as good as a 1-in-65,536 chance that random corruption passes, and real error patterns do worse than random.
Studies of real traffic have found that corrupted segments do occasionally pass both the link-layer CRC and the TCP checksum. Applications that cannot tolerate even rare silent corruption, such as file transfer or storage, should add their own end-to-end check, for example a SHA-256 hash of the file or TLS, which authenticates every record.
Checksum offload and what you see in captures
Modern network cards compute and verify checksums in hardware, a feature called checksum offload. The operating system hands the card a segment with a placeholder checksum, and the card fills in the real value as the frame leaves.
If you capture outgoing traffic on the same machine with a tool such as Wireshark or tcpdump, the capture happens before the card finishes the job. The tool then reports "incorrect checksum" on packets that are fine on the wire. This is a capture artifact. Check packets captured on another machine, or disable offload with ethtool -K <interface> tx off while debugging.
Summary of the main points
- The transport checksum is an end-to-end check that complements the per-hop link-layer CRC.
- The algorithm is a 16-bit one's complement sum, inverted. A receiver verifies a segment by summing everything, including the stored checksum, and expecting zero after inversion.
- TCP and UDP include a pseudo-header with the IP addresses, protocol number and length, so misdelivered segments fail the check.
- A failed check silently discards the segment. UDP loses the data. TCP recovers through retransmission.
- The checksum is weak against reordering and compensating errors, so integrity-critical applications add their own check.
Exercise
Compute the 16-bit Internet checksum of the two words 0x1234 and 0xFFFF, showing how the carry is handled. Then say what a receiver sums to when it checks the segment, with the checksum included.
Show answer
0x1234 + 0xFFFF = 0x11233. The carry above bit 15 (the leading 1) is added back: 0x1233 + 0x0001 = 0x1234. Inverting gives 0xEDCB, which is the checksum. The receiver adds 0x1234 + 0xFFFF + 0xEDCB. The first two give 0x1234 after folding, and 0x1234 + 0xEDCB = 0xFFFF. The sum is all ones, which inverts to 0, so the segment passes.
Exercise
A UDP sender over IPv4 computes a checksum of exactly 0x0000. What value does it put in the header, and why? What does this value do to a receiver that skips checks when the field is zero?
Show answer
It transmits 0xFFFF. A zero field in UDP over IPv4 means "no checksum was computed", so sending 0x0000 would make the receiver skip verification. In one's complement arithmetic 0xFFFF is also zero (negative zero), so the receiver's check still works, and it verifies the datagram normally.
Exercise
Why do the TCP and UDP checksums include a pseudo-header with the IP addresses, even though the addresses are not part of the TCP or UDP header? Name one device whose behavior makes this relevant.
Show answer
The pseudo-header makes the checksum depend on the source and destination addresses, so a segment delivered to the wrong host, or one whose IP addresses were altered, fails verification. A NAT device is relevant because it rewrites addresses and ports, so it must also update the transport checksum to match.