2005
06
08
15
00
IP CheckSum
以下摘自 http://www.netfor2.com/ipsum.htm.
但是還是有個小bug.
關於溢位的問題.因為最大可以算checksum的大小只有64K bytes,
如果超過這個大小,就會算出錯誤的檢查碼.
看了看,似乎怎樣都會有問題.
除非犧牲效能,每次相加時,把溢位的部份加回去.
PS: 紅色的部份是我修改過的.
IP CHECKSUM CALCULATION
The IP Header Checksum is computed on the header fields only.
Before starting the calculation, the checksum fields (octets 11 and 12)
are made equal to zero.
In the example code,
u16 buff[] is an array containing all octets in the header with octets 11 and 12 equal to zero.
u16 len_ip_header is the length (number of octets) of the header.
/*
**************************************************************************
Function: ip_sum_calc
Description: Calculate the 16 bit IP sum.
***************************************************************************
*/
typedef unsigned short u16;
typedef unsigned long u32;
typedef unsugned char u8;
u16 ip_sum_calc(u16 len_ip_header, u8 buff[])
{
u16 word16;
u32 sum=0;
u16 i;
// make 16 bit words out of every two adjacent 8 bit words in the packet
// and add them up
for (i=0;i<len_ip_header;i=i+2){
word16 =((buff[i]<<8)&0xFF00)+(buff[i+1]&0xFF);
sum = sum + (u32) word16;
}
// take only 16 bits out of the 32 bit sum
while (sum>>16)
sum = (sum & 0xFFFF)+(sum >> 16);
// one's complement the result
sum = ~sum;
return ((u16) sum);
}