networking · advanced · ~35 min

Compute the IPv4/TCP one's-complement checksum

One's complement arithmetic + carry-fold.

Challenge

Compute the 16-bit one's complement Internet checksum over a buffer:

uint16_t inet_checksum(const uint8_t *buf, size_t len);

Steps:

  1. Sum the buffer as 16-bit big-endian words. If len is odd, the last byte is the high byte of a zero-padded word.
  2. While the running sum has bits above 16, add the carry (sum = (sum & 0xFFFF) + (sum >> 16)).
  3. Return the one's complement (~sum) as a 16-bit value.

Why this matters

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.

Input format

Arbitrary bytes.

Output format

The 16-bit checksum.

Constraints

Treat bytes as unsigned. The order matters: high byte first.

Starter code

#include <stdint.h>
#include <stddef.h>
uint16_t inet_checksum(const uint8_t *buf, size_t len) { /* TODO */ return 0; }

Common mistakes

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).

Edge cases to handle

Empty buffer → checksum is 0xFFFF (~0). Single byte → padded to a word.

Complexity

O(len).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.