Internet checksum 因特网检验和的算法

Internet校验和算法:
1.待校验的相邻字节成对组成16比特整数并计算其和的二进制反码(二进制反码求和).
2.生成校验和,校验和区域本身应当先置0,并和待校验数据相加,其和进行二进制反码运算后赋给校验和区域.
3.检查校验和,将所有字节,包括校验和,进行相加并求二进制反码.如果结果为全1(即二进制反码算术中的0),检查通过.

二进制反码求和:从低位到高位逐列进行和计算,如果最高位(16位)进位,则得到的结果加1,一直循环到最高位没有进位为止.最后把得到的结果取反.程序实现如下:

short checksum(unsigned short *buf, int nwords)
{
    unsigned long sum;
    for (sum = 0; nwords > 0; nwords--)
         sum += *buf++;
    while (sum >> 16)  
         sum = (sum >> 16) + (sum & 0xffff);
    return ~sum;
}

(1) Adjacent octets to be checksummed are paired to form 16-bit integers, and the 1’s complement sum of these 16-bit integers is formed.

(2) To generate a checksum, the checksum field itself is cleared, the 16-bit 1’s complement sum is computed over the octets concerned, and the 1’s complement of this sum is placed in the checksum field.

(3) To check a checksum, the 1’s complement sum is computed over the same set of octets, including the checksum field. If the result is all 1 bits (-0 in 1’s complement arithmetic), the check succeeds.

Packet

01 00 F2 03 F4 F5 F6 F7 00 00

(00 00 is the checksum field)

Form the 16-bit words

0100 F203 F4F5 F6F7

Calculate 2’s complement sum

0100 + F203 + F4F5 + F6F7 = 0002 DEEF (store the sum in a 32-bit word)

Add the carries (0002) to get the 16-bit 1’s complement sum

DEEF + 002 = DEF1

Calculate 1’s complement of the 1’s complement sum

~DEF1 = 210E

We send the packet including the checksum 21 0E

01 00 F2 03 F4 F5 F6 F7 21 0E

At the receiving

0100 + F203 + F4F5 + F6F7 + 210E = 0002 FFFD
FFFD + 0002 = FFFF

which checks OK.

你可能感兴趣的:(linux,网络)