Internet checksum Algorithm Implementation

Source: Internet
Author: User

Enhanced Internet checksum algorithm 8.10.20

For the principles, see:

Internet checksum algorithm: http://blog.csdn.net/microtong/archive/2008/10/20/3112139.aspx

Features of Internet checksum algorithm: http://blog.csdn.net/microtong/archive/2008/10/20/3112157.aspx

  1. /*
  2. Pbuffer is the start address of the datagram to be verified.
  3. Nsize specifies the length of the verification content, in bytes
  4. */
  5. Unsigned short checksum_calculating (unsigned short * pbuffer, int nsize)
  6. {
  7. Unsigned long dwcksum = 0; // 32-bit sum
  8. Unsigned char * P = (unsigned char *) & dwcksum;
  9. // Accumulate in two bytes
  10. While (nsize> 1)
  11. {
  12. Dwcksum + = * pbuffer ++;
  13. Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
  14. Nsize-= sizeof (unsigned short );
  15. }
  16. Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
  17. // If the total number of bytes is an odd number, add the last byte.
  18. If (nsize)
  19. {
  20. Dwcksum + = * (unsigned char *) pbuffer;
  21. Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
  22. }
  23. // Accumulate the carry in the 32-bit integer high to the 16-bit lower
  24. While (dwcksum> 16 ){
  25. Dwcksum = (dwcksum & 0 xFFFF) + (dwcksum> 16 );
  26. Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
  27. }
  28. // Obtain the inverse checksum.
  29. Dwcksum = ~ Dwcksum;
  30. Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
  31. // Returns the 16-bit checksum.
  32. Return (unsigned short) (dwcksum );
  33. }
Related Article

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.