paul | 718e374 | 2002-12-13 20:15:29 +0000 | [diff] [blame] | 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 | |
| 9 | #include <zebra.h> |
| 10 | |
| 11 | int /* return checksum in low-order 16 bits */ |
paul | 8cc4198 | 2005-05-06 21:25:49 +0000 | [diff] [blame] | 12 | in_cksum(u_short *ptr, int nbytes) |
paul | 718e374 | 2002-12-13 20:15:29 +0000 | [diff] [blame] | 13 | { |
| 14 | register long sum; /* assumes long == 32 bits */ |
| 15 | u_short oddbyte; |
| 16 | register u_short answer; /* assumes u_short == 16 bits */ |
| 17 | |
| 18 | /* |
| 19 | * Our algorithm is simple, using a 32-bit accumulator (sum), |
| 20 | * we add sequential 16-bit words to it, and at the end, fold back |
| 21 | * all the carry bits from the top 16 bits into the lower 16 bits. |
| 22 | */ |
| 23 | |
| 24 | sum = 0; |
| 25 | while (nbytes > 1) { |
| 26 | sum += *ptr++; |
| 27 | nbytes -= 2; |
| 28 | } |
| 29 | |
| 30 | /* mop up an odd byte, if necessary */ |
| 31 | if (nbytes == 1) { |
| 32 | oddbyte = 0; /* make sure top half is zero */ |
| 33 | *((u_char *) &oddbyte) = *(u_char *)ptr; /* one byte only */ |
| 34 | sum += oddbyte; |
| 35 | } |
| 36 | |
| 37 | /* |
| 38 | * Add back carry outs from top 16 bits to low 16 bits. |
| 39 | */ |
| 40 | |
| 41 | sum = (sum >> 16) + (sum & 0xffff); /* add high-16 to low-16 */ |
| 42 | sum += (sum >> 16); /* add carry */ |
| 43 | answer = ~sum; /* ones-complement, then truncate to 16 bits */ |
| 44 | return(answer); |
| 45 | } |