IP header checksum calculation C implementation

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.