Protocol Analysis: IP check and algorithm
Definition: a checksum is an error correction field for the IP header. Checksums do not calculate the encapsulated data. UDP, TCP, and ICMP all have their own checksums. The header checksum field contains a 16-bit binary complement sum, which is calculated by the packet sender. The recipient will recalculate the 16-bit binary complement sum together with the original checksum. If there are no errors in the packet transmission, the result should be 1 for all 16 bits.
Code:
Unsigned short csum (unsigned char * addr,int count)
{
/ * ComputeInternet Checksum for "count" bytes beginning at location "addr". , /
Registerlong sum = 0
While (count > 1)
{
/ * This is the inner loop * /
Sum + = * (unsigned short) addr++
Count-= 2
}
/ * Add leftover byte,if any * /
If (count > 0) / / Odd byte, considering whether the CPU mode is large or small
# if BIG_ENDIAN
Sum+= (* (unsigned char *) addr) 16)
Sum = (sum & 0xffff) + (sum > > 16)
Return ~ sum
}