看计算机网络相关的书,每次看到IP或者UDP报头校验和时,都一瞥而过,以为相当简单。可是今天一看真傻眼了,怎么算的,为什么用反码不用补码还真不知道怎么回事。
算法的C语言实现:
unsignedshortcsum(unsignedchar *addr,intcount)
{
/* Compute Internet Checksum for "count" bytes
* beginning at location "addr".
*/
register long sum = 0;
while( count > 1 ) {
/* This is the inner loop */
sum += * (unsigned short) addr++;
count -= 2;
}
/* Add left-over byte, if any */
if( count > 0 )
sum += * (unsigned char *) addr;
/* Fold 32-bit sum to 16 bits */
while (sum>>16)
sum = (sum & 0xffff) + (sum >> 16);
checksum = ~sum;
return checksum;
}
计算校验和的算法思路:
1. 将原Checksum位置全部置0,把报头中每16bit作为一组,当成无符号数