Back to ComputerTerms

IP Checksum

Process

The IpCheckSum uses the OnesComplement representation of positive and negative numbers.

Given a buffer that is a multiple of 16 bits such as an IP packet header, create a OnesComplement sum of each of the 16 bit words. After you have added all the 16 bit words of the buffer, make sure the result is only 16 bits and return its complement. This is the value added to the checksum field. Now when you add all the pieces, you should get -0 in 1s complement parlance.

The Algorithm

   1 cksum(u_short *buf, int count) {
   2   register u_long sum = 0;
   3 
   4   while(count--) {
   5     sum += *buf++    /* this adds the 16 bit value of *buf and then increments the pointer */
   6     if (sum & 0xFFFF0000) { /* if we carried a bit over the 16 bit limit */
   7       sum &= 0xFFFF;
   8       sum++;
   9     }
  10   }
  11   return ~(sum & 0xFFFF);

Example

Embedded application/pdf

Back to ComputerTerms

IpCheckSum (last edited 2020-01-26 23:12:38 by scot)