checksum.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * Checksum routine for Internet Protocol family headers (C Version).
  3. *
  4. * Refer to "Computing the Internet Checksum" by R. Braden, D. Borman and
  5. * C. Partridge, Computer Communication Review, Vol. 19, No. 2, April 1989,
  6. * pp. 86-101, for additional details on computing this checksum.
  7. */
  8. #include <zebra.h>
  9. #include "checksum.h"
  10. int /* return checksum in low-order 16 bits */
  11. in_cksum(void *parg, int nbytes)
  12. {
  13. u_short *ptr = parg;
  14. register long sum; /* assumes long == 32 bits */
  15. u_short oddbyte;
  16. register u_short answer; /* assumes u_short == 16 bits */
  17. /*
  18. * Our algorithm is simple, using a 32-bit accumulator (sum),
  19. * we add sequential 16-bit words to it, and at the end, fold back
  20. * all the carry bits from the top 16 bits into the lower 16 bits.
  21. */
  22. sum = 0;
  23. while (nbytes > 1) {
  24. sum += *ptr++;
  25. nbytes -= 2;
  26. }
  27. /* mop up an odd byte, if necessary */
  28. if (nbytes == 1) {
  29. oddbyte = 0; /* make sure top half is zero */
  30. *((u_char *) &oddbyte) = *(u_char *)ptr; /* one byte only */
  31. sum += oddbyte;
  32. }
  33. /*
  34. * Add back carry outs from top 16 bits to low 16 bits.
  35. */
  36. sum = (sum >> 16) + (sum & 0xffff); /* add high-16 to low-16 */
  37. sum += (sum >> 16); /* add carry */
  38. answer = ~sum; /* ones-complement, then truncate to 16 bits */
  39. return(answer);
  40. }