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。否則,報頭在傳輸過程中出錯。

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