Get the App
SLTechnology News&Howtos  ›  Network Security  › 

IP checksum calculation

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

Today's class mentioned IP head checksum how to calculate, it is really not very clear, so went to the Internet to check some information, sort out the records.

The calculation of the first checksum of IP consists of two steps: XOR and inversion, specifically.

1. IP header takes 16 bits as a unit, adding module 2 one by one (equivalent to XOR)

two。 The result is inverted and put into the checksum field as a checksum

3. The checksum field is filled with zeros when the checksum field is initially calculated

This is how the checksum is calculated for the sender, and for the receiver, the verification is simple:

1. The received IP header is summed up one by one in 16 bits.

two。 If the result is 1, the check is correct, otherwise the error is discarded.

The principle is very simple, the receiver's calculation object is the inverse XOR of An and A, and the result is, of course, 1!

Specific examples of program implementation are as follows:

SHORT checksum (USHORT* buffer, int size)

{

Unsigned long cksum = 0

/ / add every 16 bits

While (size > 1)

{

Cksum + = * buffer++

Size-= sizeof (USHORT)

}

/ / the last odd number section

If (size)

{

Cksum + = * (UCHAR*) buffer

}

Cksum = (cksum > > 16) + (cksum&0xffff); / / add high 16bit and low 16bit

Cksum + = (cksum > > 16); / / add the high 16bit to the low 16bit to ensure that the high 16 bits are 0

Return (USHORT) (~ cksum); / / finally invert the result to get checksum

}

Tags: Result header field unit clear example principle sender odd byte object message receiver receiver program data high bit verification Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Microsoft MySQL Xiaomi MariaDB