IP包校验和

RFC 1071中定义了Checksum的算法:

   (1)  Adjacent octets to be checksummed are paired to form 16-bit
integers, and the 1's complement sum of these 16-bit integers is
formed.

(2) To generate a checksum, the checksum field itself is cleared,
the 16-bit 1's complement sum is computed over the octets
concerned, and the 1's complement of this sum is placed in the
checksum field.

(3) To check a checksum, the 1's complement sum is computed over the
same set of octets, including the checksum field. If the result
is all 1 bits (-0 in 1's complement arithmetic), the check
succeeds.



算法的C语言实现:

{
/* Compute Internet Checksum for "count" bytes
* beginning at location "addr".
*/
register long sum = 0;

while( count > 1 ) {
/* This is the inner loop */
sum += * (unsigned short) addr++;
count -= 2;
}

/* Add left-over byte, if any */
if( count > 0 )
sum += * (unsigned char *) addr;

/* Fold 32-bit sum to 16 bits */
while (sum>>16)
sum = (sum & 0xffff) + (sum >> 16);

checksum = ~sum;

return checksum;
}


计算校验和的算法思路:

1. 将原Checksum位置全部置0,把报头中每16bit作为一组,当成无符号数相加得到sum,若报头字节数为单数,则最后一个字节直接当8bit无符号数加到前面的sum上去。

2. 对sum右移16位,并与原sum的低16位相加,得到结果重新赋给sum。

3. 直到sum的高16位为0时,再将sum取反(反码),返回sum值作为Checksum。



接收端校验过程:


接收到的结果再进行一次上述计算,得到返回的值应该为0。否则,报头在传输过程中出错。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章