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