blob: 8c0ea521c9f1b36ee18efadfec7c864d037d7010 [file] [log] [blame]
paul718e3742002-12-13 20:15:29 +00001/*
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
11int /* return checksum in low-order 16 bits */
paul8cc41982005-05-06 21:25:49 +000012in_cksum(u_short *ptr, int nbytes)
paul718e3742002-12-13 20:15:29 +000013{
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}