根据RFC1071文档的计算方法,编写代码实现IP首部校验和的计算
计算步骤:
1.首先将IP首部中校验和字段置0
2.将IP首部每16bit进行相加,如果有进位产生,则将进位加到最低位。
3.将计算的结果取反即可
1 unsigned short checksum(int count,unsigned short* addr) 2 { 3 long sum = 0; 4 5 while(count > 1) 6 { 7 sum +=*addr++; 8 count -= sizeof(unsigned short); 9 }10 11 if(count > 0)12 {13 sum +=*(unsigned char*)addr;14 }15 16 while(sum >> 16)17 {18 sum = (sum & 0xFFFF) + (sum >> 16);19 }20 21 return (unsigned short)(~sum);22 }23 int main(int argc,char* argv[])24 {25 unsigned char IpHeader[] = "\xa1\x00\x00\x45\x00\x00\x21\x2c\x00\x00\x11\x01\x2f\x0a\x1e\xac\xfa\xff\xff\xef"; //抓包实例 检验和是0xe6e326 27 printf("0x%0x\n",checksum(sizeof(IpHeader)-1,(unsigned short *)IpHeader));28 29 return 0;30 }