linux之网络编程ICMP校验算法
1、ICMP校验算法代码
unsigned short cal_chksum(unsigned short *addr,int len)
{
int nleft = len;
int sum = 0;
unsigned short *w = addr;
unsigned short answer =0;
/*把ICMP报头二进制数据以2字节为单位累加起来*/
while(nleft > 1)
{
sum += *w++;
nleft -= 2;
}
/*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个2字节数据的高字节,这个2字节数据的低字节为0,继续累加*/
if(nleft == 1)
{
*(unsigned char *)(&answer)=*(unsigned char *)w;
sum+=answer;
}
/*校验和是以16位为单位进行求和计算的,sum是32位的,sum&0xffff是低16位,sum>>16是右移16位,取到的是高16位,相加就是高16位和低16位的和。*/
sum = (sum >> 16) + (sum & 0xffff);
/*这一步是有可能上面加的时候有进位到高16位的,再把高16位加进来。*/
sum += (sum >> 16);
/*上一步肯定不会再有进位了,即使上面sum高16位非0也不要紧,此处sum只能把低字节数赋值给answer,因为answer为16位*/
answer =~ sum;
return answer;
}
赞 (0)