1 /******************************************************************************
2 IPv4 and IPv6 Header Checksum Code
4 Copyright (C) 2013 Samuel Jero <sj323707@ohio.edu>
6 This program 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
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
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/>.
19 Author: Samuel Jero <sj323707@ohio.edu>
21 ******************************************************************************/
23 #include <arpa/inet.h>
24 #include "checksums.h"
28 #define u_int32_t uint32_t
31 #define u_int16_t uint16_t
34 //Pseudo Headers for checksums
35 struct ip6_pseudo_hdr{
36 u_char src[IP6_ADDR_LEN];
37 u_char dest[IP6_ADDR_LEN];
42 struct ip4_pseudo_hdr{
43 u_char src[IP4_ADDR_LEN];
44 u_char dest[IP4_ADDR_LEN];
50 /*From http://gitorious.org/freebsd/freebsd/blobs/HEAD/sbin/dhclient/packet.c
52 u_int32_t checksum(u_char *buf, unsigned nbytes, u_int32_t sum)
55 /* Checksum all the pairs of bytes first... */
56 for (i = 0; i < (nbytes & ~1U); i += 2) {
57 sum += (u_int16_t)ntohs(*((u_int16_t *)(buf + i)));
62 * If there's a single byte left over, checksum it, too.
63 * Network byte order is big-endian, so the remaining byte is
74 /*From http://gitorious.org/freebsd/freebsd/blobs/HEAD/sbin/dhclient/packet.c
76 u_int32_t wrapsum(u_int32_t sum)
82 u_int16_t ipv6_pseudohdr_chksum(u_char* buff, int len, u_char* dest, u_char* src, int type){
83 struct ip6_pseudo_hdr hdr;
85 //create pseudo header
86 memset(&hdr, 0, sizeof(struct ip6_pseudo_hdr));
87 memcpy(hdr.src, src, IP6_ADDR_LEN);
88 memcpy(hdr.dest, dest, IP6_ADDR_LEN);
92 //calculate total checksum
93 return wrapsum(checksum((unsigned char*)&hdr,sizeof(struct ip6_pseudo_hdr),checksum(buff,len,0)));
96 u_int16_t ipv4_pseudohdr_chksum(u_char* buff, int len, u_char* dest, u_char* src, int type){
97 struct ip4_pseudo_hdr hdr;
99 //create pseudo header
100 memset(&hdr, 0, sizeof(struct ip4_pseudo_hdr));
101 memcpy(hdr.src, src, IP4_ADDR_LEN);
102 memcpy(hdr.dest, dest, IP4_ADDR_LEN);
106 //calculate total checksum
107 return wrapsum(checksum((u_char*)&hdr,sizeof(struct ip4_pseudo_hdr),checksum(buff,len,0)));
110 u_int16_t ipv4_chksum(u_char* buff, int len){
111 return wrapsum(checksum(buff,len,0));