IP packet checksum algorithm C # (formerly)

Source: Internet
Author: User
For the sake of pseudo IP, we specially made an IP package and used C # to rewrite the IP header checksum algorithm.
Document 1:
IP Header Format:
Version Number (4 digits)
IP header length (4 digits)
Service type (8 bits)
Packet Length (16 bits)
Id segment (16 bits)
Flag (16 bits)
Survival time (8 digits)
Transmission Protocol (8 bits)
Header checksum (16 bits)
Sending address (16 digits)
Destination Address (16 bits)
Option
Fill

Document 2:
The IP protocol uses a unified verification algorithm. The calculation is relatively simple: Set the checksum initial value to 0, and then calculate the checksum for every 16 bits or if the result is reversed. During verification, the data (including checksum) is summed according to the same algorithm. If the result is 0, the data is correct. If the value is not 0, a communication error occurs and the packet must be discarded.

Algorithm source code:

Public static UInt16 checksum (UInt16 [] buffer, int size)
{
Int32 cksum = 0;
Int counter;
Counter = 0;
While (size> 0)
{
UInt16 val = buffer [counter];
Cksum + = Convert. ToInt32 (buffer [counter]);
Counter + = 1;
Size =-1;
}
Cksum = (cksum> 16) + (cksum & 0 xffff );
Cksum + = (cksum> 16 );
Return (UInt16 )(~ Cksum );
}

Note: The buffer array is the entire IP package array and needs to be converted to UInt16 []; size is the length of the buffer array.
The method for converting byte [] to UInt16 [] is relatively simple. We will not describe it here.

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.