简体   繁体   中英

ICMP header and IP header checksum calculations

Are icmp header checksum and ip header checksum calculation methods are same? I mean, they may be similar. But I found this code for ip header checksum. Can I use this code for icmp header checksum too? Any other help would be great.

     unsigned short cksum(struct ip *ip, int len){
       long sum = 0;  /* assume 32 bit long, 16 bit short */

       while(len > 1){
         sum += *((unsigned short*) ip)++;
         if(sum & 0x80000000)   /* if high order bit set, fold */
           sum = (sum & 0xFFFF) + (sum >> 16);
         len -= 2;
       }

       if(len)       /* take care of left over byte */
         sum += (unsigned short) *(unsigned char *)ip;

       while(sum>>16)
         sum = (sum & 0xFFFF) + (sum >> 16);

       return ~sum;
     }

RFC 791 - Internet Protocol ...

Header Checksum: 16 bits

A checksum on the header only. Since some header fields change (eg, time to live), this is recomputed and verified at each point that the internet header is processed.

The checksum algorithm is:

  The checksum field is the 16 bit one's complement of the one's complement sum of all 16 bit words in the header. For purposes of computing the checksum, the value of the checksum field is zero. 

This is a simple to compute checksum and experimental evidence indicates it is adequate, but it is provisional and may be replaced by a CRC procedure, depending on further experience.

Note : The "CRC procedure" was never implemented.

RFC 792 - Internet Control Message Protocol ...

Header Checksum

  The 16 bit one's complement of the one's complement sum of all 16 bit words in the header. For computing the checksum, the checksum field should be zero. This checksum may be replaced in the future. 

Note : Again, this algorithm was never replaced.

So, it's safe to assume that both algorithms are the same, and yes, you can use the same BSD code (changing the struct ip stuff for sanity's sake, of course) for calculating a ICMP header checksum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM