The IPv4 header checksum
Compute and verify the ones'-complement checksum every IPv4 header carries. A medium embedded C problem (TCP/IP fundamentals), run and graded in the browser.
medium · TCP/IP fundamentals · networking · ipv4 · checksum
Every IPv4 header carries a 16-bit Internet checksum:
- treat the header as a sequence of 16-bit big-endian words, with the checksum field (bytes 10 and 11) taken as 0,
- add them up, folding any carry above 16 bits back into the low 16 bits (ones'-complement addition),
- the checksum is the bitwise NOT of the sum.
A receiver adds up the whole header including the checksum; the result folds to 0xFFFF if the header is intact.
Write ip_checksum(hdr, len), which computes the checksum (ignoring bytes 10 and 11), and ip_header_ok(hdr, len), which verifies a received header. len is even.
Starter code
uint16_t ip_checksum(const uint8_t *hdr, int len) {
uint16_t sum = 0;
for (int i = 0; i < len; i += 2) {
if (i == 10) continue;
sum += (uint16_t)((hdr[i] << 8) | hdr[i + 1]);
}
return (uint16_t)~sum;
}
bool ip_header_ok(const uint8_t *hdr, int len) {
return ip_checksum(hdr, len) == ((hdr[10] << 8) | hdr[11]);
}Example tests
A UDP packet's header
uint16_t c = ip_checksum(h, 20);
printf("checksum 0x%04X\n", c);Expected output:
checksum 0xB861Verify, then corrupt
uint16_t c = ip_checksum(h, 20);
h[10] = c >> 8; h[11] = c & 0xFF;
printf("%d\n", ip_header_ok(h, 20));
h[15] ^= 0x01;
printf("%d\n", ip_header_ok(h, 20));
h[15] ^= 0x01; h[10] = h[11] = 0;Expected output:
1
0Learn it first
- TCP/IP fundamentals · Layers, the handshake, flow and congestion control, and lwIP.
More TCP/IP fundamentals problems
- Router: the IPv4 header checksum · Compute the one's-complement checksum every IPv4 router checks and rewrites on each packet.