networking · advanced · ~15 min

Internet checksum (16-bit ones-complement)

Implement the checksum used by IP/UDP/TCP.

Challenge

Compute the 16-bit ones-complement Internet checksum — the same algorithm IP, UDP, and TCP headers use.

Task

Implement unsigned short inet_checksum(const unsigned char *data, int n):

  1. Sum the data as big-endian 16-bit words into a wider accumulator.
  2. If n is odd, treat the final lone byte as the high byte of a word.
  3. Fold the carries back in (end-around carry) until the sum fits in 16 bits.
  4. Return the bitwise NOT of the folded sum.

Input

  • data: the bytes to checksum.
  • n: number of bytes.

Output

The 16-bit ones-complement checksum.

Example

{0x12, 0x34}              ->  0xEDCB
{0x00, 0x00}              ->  0xFFFF
{0xFF, 0xFF, 0xFF, 0xFF}  ->  0x0000   (carry folds back)

Edge cases

  • An odd byte count: the trailing byte becomes the high byte of the last word.

Input format

data: the bytes to checksum; n: the byte count.

Output format

The 16-bit ones-complement checksum (big-endian words, end-around carry, then NOT).

Constraints

Sum big-endian 16-bit words; pad an odd trailing byte as the high byte; fold carries; return ~sum.

Starter code

unsigned short inet_checksum(const unsigned char *data, int n) {
    /* TODO */
    return 0;
}

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