3
0

inet_cksum.c 898 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. /*
  2. * Checksum routine for Internet Protocol family headers (C Version)
  3. *
  4. * Licensed under GPLv2, see file LICENSE in this source tree.
  5. */
  6. #include "libbb.h"
  7. uint16_t FAST_FUNC inet_cksum(const void *ptr, int nleft)
  8. {
  9. const uint16_t *addr = ptr;
  10. /*
  11. * Our algorithm is simple, using a 32 bit accumulator,
  12. * we add sequential 16 bit words to it, and at the end, fold
  13. * back all the carry bits from the top 16 bits into the lower
  14. * 16 bits.
  15. */
  16. unsigned sum = 0;
  17. while (nleft > 1) {
  18. sum += *addr++;
  19. nleft -= 2;
  20. }
  21. /* Mop up an odd byte, if necessary */
  22. if (nleft == 1) {
  23. if (BB_LITTLE_ENDIAN)
  24. sum += *(uint8_t*)addr;
  25. else
  26. sum += *(uint8_t*)addr << 8;
  27. }
  28. /* Add back carry outs from top 16 bits to low 16 bits */
  29. sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
  30. sum += (sum >> 16); /* add carry */
  31. return (uint16_t)~sum;
  32. }