Skip to content

Instantly share code, notes, and snippets.

@ms0g
Created July 30, 2020 11:33
Show Gist options
  • Save ms0g/067786b676cc4359528c99e18d9e0fb5 to your computer and use it in GitHub Desktop.
Save ms0g/067786b676cc4359528c99e18d9e0fb5 to your computer and use it in GitHub Desktop.
Ipv4 header checksum calculation
/**
* Compute Internet Checksum for "count" bytes
* beginning at location "addr".
* @param addr start of the ip header
* @param count ip header size
* @return Taking the ones' complement (flipping every bit) yields 0000,
* which indicates that no error is detected.
*/
uint16_t checksum(void *addr, int count) {
uint32_t sum = 0;
auto *ptr_16 = static_cast<uint16_t *>(addr);
for (; count > 1; count -= 2) {
// This is the inner loop
sum += *ptr_16++;
}
// Add left-over byte, if any
if (count > 0)
sum += *static_cast<uint8_t *>(addr);
// Fold 32-bit sum to 16 bits
while (sum >> 16u)
sum = (sum & 0xffffu) + (sum >> 16u);
return ~sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment