ICMP header 和 IP header 校验和计算

ICMP header and IP header checksum calculations

icmp header checksum和ip header checksum的计算方法一样吗?我的意思是,它们可能很相似。但是我找到了 this ip header 校验和的代码。我也可以将此代码用于 icmp header 校验和吗?任何其他帮助都会很棒。

     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 (e.g., 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.

注意:“CRC 程序”从未实现。

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.

注意:同样,这个算法从未被替换过。

因此,可以安全地假设这两种算法是相同的,是的,您可以使用相同的 BSD 代码(当然,为了理智起见更改 struct ip 内容)来计算 ICMP header校验和。