The Calculation of IP header checksum has a complete description in rfc791,
Header checksum: 16 bits
A checksum on the header only. Since some header fields change
(E.g., time to live), this is recomputed and verified at each point
That the Internet header is processed.
The Checksum algorithm is:
The Checksum field is the 16 bit one's complement of the one's
Complement sum of all 16 bit words in the header. For purposes
Computing the checksum, the value of the checksum field is zero.
This is a simple to compute checksum and experimental evidence
Indicates it is adequate, but it is provisional and may be replaced
By a CRC procedure, depending on further experience.
The general significance is as follows:
Checksum is only related to the IP header. When the data in the header is changed, you need to re-calculate the checksum.
Checksum is the sum of all 16-bit data starting from the first 0th bits in the IP header. Before calculation, set the checksum value to 0.
Code:
_Int16 GetIpCheckSum( Byte *ptr, int size){int cksum = 0;int index = 0;*(ptr + 10) = 0;*(ptr + 11) = 0;if(size % 2 != 0)return 0;while(index < size){ cksum += *(ptr + index + 1);cksum += *(ptr + index) << 8;index += 2;}while(cksum > 0xffff){cksum = (cksum >> 16) + (cksum & 0xffff);}return ~cksum;}
PS: before sending the message, you need to convert the result to the network order.