Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Checksum algorithm of IP

Shulou Source: shulou.com Published: 2022-06-01 05:17:41 10月04日 Update

The checksum algorithms of protocols such as IP/ICMP/IGMP/TCP/UDP are the same, and the algorithms are as follows:

When sending data, in order to calculate the checksum of IP packets. The following steps should be followed:

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

(2) the header is regarded as a 16-bit number, and the binary inverse code is summed in turn.

(3) store the result in the checksum field.

When receiving data, it is relatively easy to calculate the checksum of the packet, as follows:

(1) treat the header as a 16-bit number, and then sum the binary inverse code in turn, including the checksum field.

(2) check whether the result of the calculated checksum is equal to zero (the inverse code should be 16 ones)

(3) if it is equal to zero, it means that it is divisible and the check is correct. Otherwise, the checksum is wrong and the protocol stack discards the packet.

The so-called binary inverse code summation means that the binary summation is carried out first, and then the sum and inversion are carried out.

IP Datagram format

Suppose the IP header is: 4500 0046 17d9 0000 4011 ec1d (check field) ac1c 0f3b ac1c 0f3d

Calculate:

4500 + 0046 + 17d9 + 0000 + 4011 + ec1d + ac1c + 0f3b + ac1c + 0f3d

The sum taken out 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:

44500 + 0046 + 17d9 + 0000 + 4011 + ec1d + ac1c + 0f3b + ac1c + 0f3d is added to FFFF again, and the result is all-in-one and correct.

Now suppose a Datagram is 45 00 05 D4 CA E0 40 00 75 06 70 D2 CA 62 39 64 C0 A8 00 02

According to the format of the IP Datagram, we can see that its first check field is 70D2. How is it calculated?

Method: we replace the first check field, 70D2, with 0000.

4500+05D4+CAE0+4000+7506+0000+CA62+3964+C0A8+0002=38F2A

Then the one who comes out and the last four are added in hexadecimal, 8F2A+0003=8F2D.

Finally, use FFFF to subtract the calculated result, that is, FFFF-8F2D=70D2.

Code implementation

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)

}

Tags: Data field binary inverse code result algorithm unit number method format step check same number code again addition hexadecimal that is error Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Docker OPPO Reno NVidia macOS