networking · advanced · ~15 min
Implement the checksum used by IP/UDP/TCP.
Compute the 16-bit ones-complement Internet checksum — the same algorithm IP, UDP, and TCP headers use.
Implement unsigned short inet_checksum(const unsigned char *data, int n):
n is odd, treat the final lone byte as the high byte of a word.data: the bytes to checksum.n: number of bytes.The 16-bit ones-complement checksum.
{0x12, 0x34} -> 0xEDCB
{0x00, 0x00} -> 0xFFFF
{0xFF, 0xFF, 0xFF, 0xFF} -> 0x0000 (carry folds back)
data: the bytes to checksum; n: the byte count.
The 16-bit ones-complement checksum (big-endian words, end-around carry, then NOT).
Sum big-endian 16-bit words; pad an odd trailing byte as the high byte; fold carries; return ~sum.
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.