Calculation Method of TCP/IP checksum

Source: Internet
Author: User
When I read "TCP/IP explanation", I saw that the IP header checksum algorithm is called "sum of every 16 bits." So I thought that every part of the algorithm was first summed up. The write process is as follows: (take the following array as an example: Unsigned short a [10] = {0x4500, 0x059a, 0x82b9, 0X4000, 0x3206, 0x4f79, 0xa66f, 0x08ee, 0xc0a8, 0x0126}; because the first IP Minister 20b is 10 hexadecimal numbers, this is the verification part of the checksum)

  1. Unsigned short Re = 0;

  2. For (INT I = 0; I <10; I ++)
  3. Re + = ~ A [I];
  4. Re = ~ Re;

This is an incorrect practice. (I understand that "inverse code summation" is the first anticode addition before summation)

Then I made the following program:

  1. Unsigned short Re = 0;
  2. For (INT I = 0; I <10; I ++)
  3. Re + = A [I];
  4. Re = ~ Re;

This unsigend short is calculated based on the 16 power (65536) of model 2. The result calculation is still incorrect.

Then, I read the materials and made the following improvements:

  1. Int sum = 0;
  2. Unsigned short result = 0;
  3. For (INT I = 0; I <10; I ++)
  4. {
  5. Sum + = A [I];
  6. Sum = sum % 65535;
  7. }
  8. Result = (unsigned short) sum;
  9. Result = ~ Result;

This time, the result is 0 xFFFF, all 1, indicating that the checksum is correct.

It turns out that the decimal algorithm of this anticode is based on (2 to the Npower-1), that is, the 16-bit anti-code arithmetic is 65536-1 = 65535 (65536 is the 16 power of 2). Then, the above process is to "first obtain the part and then obtain its anti-code ", or, in turn, we can understand the "first-to-sum inverse code, then sum", that is, the reverse code summation.

The second program above is the addition operation of the unsinged short. The default value is the modulo 65536, so it is incorrect.

As for the first procedure, I had to learn Chinese and English well because of my misunderstanding.

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.