Question regarding ip checksum code

Posted by looktt on Stack Overflow See other posts from Stack Overflow or by looktt
Published on 2010-04-05T19:17:55Z Indexed on 2010/04/05 19:23 UTC
Read the original article Hit count: 302

Filed under:
|
|
unsigned short  /* this function generates header checksums */
csum (unsigned short *buf, int nwords)
{
  unsigned long sum;
  for (sum = 0; nwords > 0; nwords--) // add words(16bits) together
    sum += *buf++;
  sum = (sum >> 16) + (sum & 0xffff);  //add carry over
  sum += (sum >> 16);                  //what does this step do??? add possible left-over   
                                       //byte? But isn't it already added in the loop (if 
                                       //any)?
  return ((unsigned short) ~sum);
}
  1. I assume nwords in the number of 16bits word, not 8bits byte (if there are odd byte, nword is rounded to next large), is it correct?
  2. The line sum = (sum >> 16) + (sum & 0xffff) is to add carry over to make 16bit complement
  3. sum += (sum >> 16); What's the purpose of this step? Add left-over byte? How?

Thanks!

© Stack Overflow or respective owner

Related posts about ip

Related posts about header