定義:校驗和是針對IP報頭的糾錯字段。校驗和不計算被封裝的數據,UDP、TCP和ICMP都有各自的校驗和。報頭校驗和字段包含一個16位二進制補碼和,這是由數據包發送者計算得到的。接受者將連同原始校驗和重新進行16位二進制補碼和的計算。如果數據包傳輸中沒有發生錯誤,那麼結果應該16位全部爲1。
代碼:
unsigned short csum(unsigned char *addr,int count)
{
/* ComputeInternet Checksum for "count" bytes beginning at location"addr". */
registerlong sum = 0;
while( count> 1 )
{
/* This is the inner loop */
sum += * (unsigned short) addr++;
count -= 2;
}
/* Add leftover byte,if any */
if(count>0) // 奇數字節,考慮CPU大端還是小端模式
#if BIG_ENDIAN
sum+=(*(unsigned char *)addr)<<8;
#else
sum+=*(unsigned char *)addr;
#endif
/* Fold32-bit sum to 16 bits */
while(sum>>16)
sum = (sum & 0xffff) + (sum >>16);
return ~sum;
}