Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Calculation of IP header checksum

Shulou Source: shulou.com Published: 2022-06-01 04:07:51 10月01日 Update

The calculation method of IP header checksum:

Algorithm:

SHORT checksum (USHORT* buffer, int size)

{

Unsigned long cksum = 0

While (size > 1)

{

Cksum + = * buffer++

Size-= sizeof (USHORT)

}

If (size)

{

Cksum + = * (UCHAR*) buffer

}

Cksum = (cksum > > 16) + (cksum&0xffff)

Cksum + = (cksum > > 16)

Return (USHORT) (~ cksum)

}

(1) set the checksum field of IP packet to 0;

(2) the head is regarded as a 16-bit number, and the binary sum is carried out in turn (note: when summing, the carry of the highest bit should be saved, so the addition should be 32-bit addition);

(3) add the carry (the highest carry) generated in the above addition process to the low 16 bits (when using 32 bit addition, that is, the high 16 bits and the low 16 bits are added, and then the carry generated by the highest bit of the addition is added to the low 16 bits)

(4) if the above sum is reversed, the checksum will be obtained.

Example:

IP header:

45 00 00 31

89 F5 00 00

6e 06 00 00 (check field)

DE B7 45 5D-> 222.183.69.93

C0 A8 00 DC-> 192.168.0.220

Calculate:

4500 + 0031 + 89F5 + 0000 + 6e06 + 0000 + DEB7 + 455D + C0A8 + 00DC = 3 22C4

0003 + 22C4 = 22C7

~ 22C7 = DD38-> is the checksum that should be filled

When receiving an IP packet, to check whether the IP header is correct, check the IP header, using the same method as above:

Calculate:

4500 + 0031 + 89F5 + 0000 + 6E06 + DD38 + DEB7 + 455D + C0A8 + 00DC = 3 FFFC

0003 + FFFC = FFFF

Tags: Addition maximum field data method binary example unit number algorithm process middle class should be checked checked Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno macOS MariaDB vpn NVidia