Baruch Siach | e8f3633 | 2011-09-07 17:52:37 +0200 | [diff] [blame] | 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 | |
| 7 | #include "libbb.h" |
| 8 | |
| 9 | uint16_t FAST_FUNC inet_cksum(uint16_t *addr, int nleft) |
| 10 | { |
| 11 | /* |
| 12 | * Our algorithm is simple, using a 32 bit accumulator, |
| 13 | * we add sequential 16 bit words to it, and at the end, fold |
| 14 | * back all the carry bits from the top 16 bits into the lower |
| 15 | * 16 bits. |
| 16 | */ |
| 17 | unsigned sum = 0; |
| 18 | while (nleft > 1) { |
| 19 | sum += *addr++; |
| 20 | nleft -= 2; |
| 21 | } |
| 22 | |
| 23 | /* Mop up an odd byte, if necessary */ |
Denys Vlasenko | 0d0260f | 2011-09-08 10:59:26 +0200 | [diff] [blame] | 24 | if (nleft == 1) { |
| 25 | if (BB_LITTLE_ENDIAN) |
| 26 | sum += *(uint8_t*)addr; |
| 27 | else |
| 28 | sum += *(uint8_t*)addr << 8; |
| 29 | } |
Baruch Siach | e8f3633 | 2011-09-07 17:52:37 +0200 | [diff] [blame] | 30 | |
| 31 | /* Add back carry outs from top 16 bits to low 16 bits */ |
| 32 | sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ |
| 33 | sum += (sum >> 16); /* add carry */ |
| 34 | |
| 35 | return (uint16_t)~sum; |
| 36 | } |