Router: the IPv4 header checksum
Compute the one's-complement checksum every IPv4 router checks and rewrites on each packet. A medium embedded C problem (TCP/IP fundamentals), run and graded…
medium · TCP/IP fundamentals · checksum · ones-complement · ipv4 · product
Product: Home router (Telecom and networking)
Requirement. The router checks every IPv4 header it receives and drops damaged ones, and recomputes the checksum after changing a header (the time-to-live drops by one at every hop).
Compute the checksum of the len-byte header (len is even): add the header as 16-bit words, high byte first, treating the checksum field itself (bytes 10 and 11) as zero; fold any carries above 16 bits back into the low 16 bits until none are left; return the bitwise NOT of the result.
Starter code
uint16_t ipv4_checksum(const uint8_t *h, size_t len) {
uint16_t sum = 0;
for (size_t i = 0; i < len; i++)
if (i != 10 && i != 11) sum += h[i];
return (uint16_t)~sum;
}Example tests
A UDP packet's header
uint8_t h[20] = { 0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11,
0xB8, 0x61, 0xC0, 0xA8, 0x00, 0x01, 0xC0, 0xA8, 0x00, 0xC7 };
printf("%04X\n", ipv4_checksum(h, 20));Expected output:
B861A TCP packet's header
uint8_t h[20] = { 0x45, 0x00, 0x00, 0x3C, 0x1C, 0x46, 0x40, 0x00, 0x40, 0x06,
0x00, 0x00, 0xAC, 0x10, 0x0A, 0x63, 0xAC, 0x10, 0x0A, 0x0C };
printf("%04X\n", ipv4_checksum(h, 20));Expected output:
B1E6Learn it first
- TCP/IP fundamentals · Layers, the handshake, flow and congestion control, and lwIP.
More TCP/IP fundamentals problems
- The IPv4 header checksum · Compute and verify the ones'-complement checksum every IPv4 header carries.