-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathCheckSum.cpp
60 lines (54 loc) · 1.55 KB
/
CheckSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "CheckSum.h"
#include <stdio.h>
struct PseudoHead{
uint8_t zero;
uint8_t type;
uint16_t len;
uint32_t src_ip;
uint32_t dst_ip;
};
static uint32_t CalSum(const uint8_t* buf, int len) {
uint32_t sum = 0;
const uint8_t* p = buf;
for(; len > 1; len -= 2) {
sum += (*p << 8)+ *(p + 1);
p += 2;
}
if (len == 1)
sum += *p << 8; //
//sum += *p; //
return sum;
}
static uint32_t CalPseudoHeadSum(const iphdr* pIpHead, uint8_t type) {
PseudoHead head;
head.zero = 0;
head.type = type;
head.len = htons(static_cast<uint16_t>(ntohs(pIpHead->tot_len) - pIpHead->ihl * 4));
head.src_ip = pIpHead->saddr;
head.dst_ip = pIpHead->daddr;
return CalSum((uint8_t*)&head, sizeof(PseudoHead));
}
uint16_t cksumIp(iphdr* pIpHead){
pIpHead->check = 0;
uint32_t ckSum = CalSum((uint8_t*)pIpHead, pIpHead->ihl * 4);
ckSum = (ckSum >> 16) + (ckSum & 0xffff);
ckSum += ckSum >> 16;
return htons((uint16_t)~ckSum);
}
uint16_t cksumUdp(iphdr* pIpHead, udphdr* pUdpHead){
pUdpHead->check = 0;
uint32_t ckSum = CalPseudoHeadSum(pIpHead, 0x11);
ckSum += CalSum((uint8_t*)pUdpHead, ntohs(pUdpHead->len));
ckSum = (ckSum >> 16) + (ckSum & 0xffff);
ckSum += ckSum >> 16;
return htons((uint16_t)~ckSum);
}
uint16_t cksumTcp(iphdr* pIpHead, tcphdr* pTcpHead){
pTcpHead->check = 0;
uint32_t ckSum = CalPseudoHeadSum(pIpHead, 0x06);
ckSum += CalSum((uint8_t*)pTcpHead,
ntohs(pIpHead->tot_len) - pIpHead->ihl * 4);
ckSum = (ckSum >> 16) + (ckSum & 0xffff);
ckSum += ckSum >> 16;
return htons((uint16_t)~ckSum);
}