networking · advanced · ~15 min
Compute the 16-bit one's-complement Internet checksum used by IP/UDP.
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.
data of n bytes.
The 16-bit checksum.
Accumulate in a wider integer, fold sum = (sum & 0xFFFF) + (sum >> 16) until no carry remains, then return ~sum.
#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; }
Forgetting to fold the carry; padding the odd byte on the wrong side; returning the sum instead of its complement.
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.