networking · advanced · ~15 min

Internet checksum (RFC 1071)

Compute the 16-bit one's-complement Internet checksum used by IP/UDP.

Challenge

UDP and IP protect their headers with the 16-bit one's-complement checksum from RFC 1071. Implement it:

uint16_t inet_checksum16(const unsigned char *data, int n);

Sum the data as 16-bit big-endian words (pad a final odd byte with a zero low byte), fold the carries back in, and return the one's complement of the result.

Input format

data of n bytes.

Output format

The 16-bit checksum.

Constraints

Accumulate in a wider integer, fold sum = (sum & 0xFFFF) + (sum >> 16) until no carry remains, then return ~sum.

Starter code

#include <stddef.h>
#include <stdint.h>
/* 16-bit one's-complement Internet checksum (RFC 1071) over n bytes.
   Sum 16-bit big-endian words (pad a final odd byte with a zero low byte),
   fold carries, return the one's complement. */
uint16_t inet_checksum16(const unsigned char *data, int n){ (void)data;(void)n; return 0; }

Common mistakes

Forgetting to fold the carry; padding the odd byte on the wrong side; returning the sum instead of its complement.

Edge cases to handle

An odd trailing byte is the high byte of the last word; the checksum of all-zero data is 0xFFFF.

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