ICMP头和IP头校验和计算

时间:2016-03-19 19:13:18

标签: c sockets networking icmp

icmp头校验和和ip头校验和计算方法是否相同?我的意思是,他们可能是相似的。但我找到了{header}校验和的docs代码。我也可以将此代码用于icmp标头校验和吗?任何其他帮助都会很棒。

     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;
     }

1 个答案:

答案 0 :(得分:1)

RFC 791 - Internet Protocol ...

  

标头校验和:16位

     

仅限标题的校验和。由于某些标题字段更改      (例如,生存时间),在每个点重新计算和验证      处理互联网标题。

     

校验和算法是:

 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.
     

这是一个简单的计算校验和和实验证据      表示它是足够的,但它是临时的,可以更换      通过CRC程序,取决于进一步的经验。

注意:" 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头校验和。

相关问题