networking · advanced · ~35 min
One's complement arithmetic + carry-fold.
Compute the 16-bit one's complement Internet checksum over a buffer:
uint16_t inet_checksum(const uint8_t *buf, size_t len);
Steps:
len is odd, the last byte is the high byte of a zero-padded word.The 1s-complement checksum is the TCP/UDP/IP integrity check. Writing it from scratch demystifies the byte-level mechanics of every packet that crosses the internet.
Arbitrary bytes.
The 16-bit checksum.
Treat bytes as unsigned. The order matters: high byte first.
#include <stdint.h>
#include <stddef.h>
uint16_t inet_checksum(const uint8_t *buf, size_t len) { /* TODO */ return 0; }
Treating bytes as signed (sign extension wrecks the sum); forgetting to fold carries; forgetting that a 0xFFFF result is encoded as 0x0000 by sender convention (you do not need to apply that here; just return ~sum).
Empty buffer → checksum is 0xFFFF (~0). Single byte → padded to a word.
O(len).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.