Back to ComputerTerms

IP Checksum

Process

Given a buffer that is a multiple of 16 bits such as an IP packet header, create a sum and add to it the buffer 16 bits at a time. After each add, check to see if we have carried beyond 16 bits. If we have chop off the carry and increment the sum. After you have add all the 16 bit parts of the buffer, make sure the result is only 16 bits and return its complement.

The Algorithm

cksum(u_short *buf, int count) {
  register u_long sum = 0;

  while(count--) {
    sum += *buf++    /* this adds the 16 bit value of *buf and then increments the pointer */
    if (sum & 0xFFFF0000) { /* if we carried a bit over the 16 bit limit */
      sum &= 0xFFFF;
      sum++;
    }
  }
  return ~(sum & 0xFFFF);

Back to ComputerTerms