- 论坛徽章:
- 0
|
为了计算一份数据报的IP检验和,首先把检验和字段置为0。然后,对首部中每个16bit进行二进制反码求和(整个首部看成是由一串16bit的字组成),结果存在检验和字段中。当收到一份IP数据报后,同样对首部中每个16bit进行二进制反码的求和。由于接受方在计算过程中包含了发送方存在首部中的校验和。因此,如果首部在传输过程中没有发生任何差错,那么接受方计算的结果应该为全1。如果结果不是全1(即检验和错误),那么IP就丢弃收到的数据报。
下面是别人代码实现:
- /*
- **************************************************************************
- Function: ip_sum_calc
- Description: Calculate the 16 bit IP sum.
- ***************************************************************************
- */
- typedef unsigned short u16;
- typedef unsigned long u32;
- u16 ip_sum_calc(u16 len_ip_header, u16 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;
- }
- [color=Red] // take only 16 bits out of the 32 bit sum and add up the carries
- while (sum>>16)
- sum = (sum & 0xFFFF)+(sum >> 16);[/color]
- // one's complement the result
- sum = ~sum;
- return ((u16) sum);
- }
复制代码
红色部分代码的意思:把sum的高16位取出来加?是的话,我不明白为什么要这样? |
|