2 * Checksum routine for Internet Protocol family headers (C Version).
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.
12 int /* return checksum in low-order 16 bits */
13 in_cksum(void *parg, int nbytes)
16 register long sum; /* assumes long == 32 bits */
18 register u_short answer; /* assumes u_short == 16 bits */
21 * Our algorithm is simple, using a 32-bit accumulator (sum),
22 * we add sequential 16-bit words to it, and at the end, fold back
23 * all the carry bits from the top 16 bits into the lower 16 bits.
32 /* mop up an odd byte, if necessary */
34 oddbyte = 0; /* make sure top half is zero */
35 *((u_char *) &oddbyte) = *(u_char *)ptr; /* one byte only */
40 * Add back carry outs from top 16 bits to low 16 bits.
43 sum = (sum >> 16) + (sum & 0xffff); /* add high-16 to low-16 */
44 sum += (sum >> 16); /* add carry */
45 answer = ~sum; /* ones-complement, then truncate to 16 bits */
49 /* Fletcher Checksum -- Refer to RFC1008. */
50 #define MODX 4102 /* 5802 should be fine */
52 /* To be consistent, offset is 0-based index, rather than the 1-based
53 index required in the specification ISO 8473, Annex C.1 */
54 /* calling with offset == FLETCHER_CHECKSUM_VALIDATE will validate the checksum
55 without modifying the buffer; a valid checksum returns 0 */
57 fletcher_checksum(u_char * buffer, const size_t len, const uint16_t offset)
63 size_t partial_len, i, left = len;
68 if (offset != FLETCHER_CHECKSUM_VALIDATE)
69 /* Zero the csum in the packet. */
71 assert (offset < (len - 1)); /* account for two bytes of checksum */
72 csum = (u_int16_t *) (buffer + offset);
82 partial_len = MIN(left, MODX);
84 for (i = 0; i < partial_len; i++)
96 /* The cast is important, to ensure the mod is taken as a signed value. */
97 x = (int)((len - offset - 1) * c0 - c1) % 255;
105 if (offset == FLETCHER_CHECKSUM_VALIDATE)
107 checksum = (c1 << 8) + c0;
112 * Now we write this to the packet.
113 * We could skip this step too, since the checksum returned would
114 * be stored into the checksum field by the caller.
117 buffer[offset + 1] = y;
119 /* Take care of the endian issue */
120 checksum = htons((x << 8) | (y & 0xFF));