2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2010 Emmanuel Roullit.
4 * Subject to the GPL, version 2.
10 #include <netinet/in.h>
11 #include <netinet/ip.h>
15 static inline unsigned short csum(unsigned short *buf
, int nwords
)
19 for (sum
= 0; nwords
> 0; nwords
--)
21 sum
= (sum
>> 16) + (sum
& 0xffff);
27 static inline uint16_t calc_csum(void *addr
, size_t len
, int ccsum
)
29 return csum(addr
, len
>> 1);
32 static inline uint16_t csum_expected(uint16_t sum
, uint16_t computed_sum
)
37 shouldbe
+= ntohs(computed_sum
);
38 shouldbe
= (shouldbe
& 0xFFFF) + (shouldbe
>> 16);
39 shouldbe
= (shouldbe
& 0xFFFF) + (shouldbe
>> 16);
44 /* Taken and modified from tcpdump, Copyright belongs to them! */
52 do { if ((x) > 65535) \
59 sum = l_util.s[0] + l_util.s[1]; \
63 static inline u16
__in_cksum(const struct cksum_vec
*vec
, int veclen
)
66 int sum
= 0, mlen
= 0;
77 for (; veclen
!= 0; vec
++, veclen
--) {
81 w
= (const u16
*) (void *) vec
->ptr
;
84 s_util
.c
[1] = *(const u8
*) w
;
86 w
= (const u16
*) (void *) ((const u8
*) w
+ 1);
91 if ((1 & (unsigned long) w
) && (mlen
> 0)) {
94 s_util
.c
[0] = *(const u8
*) w
;
95 w
= (const u16
*) (void *) ((const u8
*) w
+ 1);
100 while ((mlen
-= 32) >= 0) {
101 sum
+= w
[0]; sum
+= w
[1]; sum
+= w
[2]; sum
+= w
[3];
102 sum
+= w
[4]; sum
+= w
[5]; sum
+= w
[6]; sum
+= w
[7];
103 sum
+= w
[8]; sum
+= w
[9]; sum
+= w
[10]; sum
+= w
[11];
104 sum
+= w
[12]; sum
+= w
[13]; sum
+= w
[14]; sum
+= w
[15];
110 while ((mlen
-= 8) >= 0) {
111 sum
+= w
[0]; sum
+= w
[1]; sum
+= w
[2]; sum
+= w
[3];
117 if (mlen
== 0 && byte_swapped
== 0)
122 while ((mlen
-= 2) >= 0) {
132 s_util
.c
[1] = *(const u8
*) w
;
137 } else if (mlen
== -1)
138 s_util
.c
[0] = *(const u8
*) w
;
148 return (~sum
& 0xffff);
151 static inline u16
p4_csum(const struct ip
*ip
, const u8
*data
, u16 len
,
154 struct cksum_vec vec
[2];
163 memset(&ph
, 0, sizeof(ph
));
166 ph
.proto
= next_proto
;
167 ph
.src
= ip
->ip_src
.s_addr
;
168 ph
.dst
= ip
->ip_dst
.s_addr
;
170 vec
[0].ptr
= (const u8
*) (void *) &ph
;
171 vec
[0].len
= sizeof(ph
);
176 return __in_cksum(vec
, 2);