Debian Codegraph @

libicmp/icmp_cksum.c

raw
1 /*
2 Copyright (C) 2001-2026 Free Software Foundation, Inc.
3
4 This file is part of GNU Inetutils.
5
6 GNU Inetutils is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or (at
9 your option) any later version.
10
11 GNU Inetutils is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see `http://www.gnu.org/licenses/'. */
18
19 #include <config.h>
20
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 unsigned short
25 icmp_cksum (unsigned char *addr, int len)
26 {
27 int sum = 0;
28 unsigned short answer = 0;
29 unsigned short *wp;
30
31 for (wp = (unsigned short *) addr; len > 1; wp++, len -= 2)
32 sum += *wp;
33
34 /* Take in an odd byte if present */
35 if (len == 1)
36 {
37 *(unsigned char *) &answer = *(unsigned char *) wp;
38 sum += answer;
39 }
40
41 sum = (sum >> 16) + (sum & 0xffff); /* add high 16 to low 16 */
42 sum += (sum >> 16); /* add carry */
43 answer = ~sum; /* truncate to 16 bits */
44 return answer;
45 }