-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip_router_protocol.cpp
88 lines (73 loc) · 2.38 KB
/
ip_router_protocol.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "ip_router_protocol.h"
void ip_router_protocol::dinternal(double t) {
if (!lower_layer_ctrl_in.empty()) {
link::Control c = lower_layer_ctrl_in.front();
this->processLinkControl(c);
lower_layer_ctrl_in.pop();
next_internal = process_link_control_time;
return;
}
if (!lower_layer_data_in.empty()) {
logger.debug("Process ip packet input.");
ip::Datagram p = lower_layer_data_in.front();
this->processIPDatagram(p);
lower_layer_data_in.pop();
next_internal = process_ip_datagram_time;
return;
}
next_internal = infinity;
output = Event(0,5);
}
/***********************************/
/********* HELPER METHODS **********/
/***********************************/
void ip_router_protocol::processIPDatagram(ip::Datagram p) {
ip::Routing_entry route;
IPv4 dest_ip = p.header.dest_ip;
logger.info("Process Ip Datagram");
// The used algorithm is the microsoft routing process that specifies 7 steps
// Step 1
if (!this->verifychecksum(p.header)) {
// silent discard
logger.info("Discard packet: checksum verification faild for packet with dest_ip: "
+ dest_ip.as_string());
return;
}
// Step 2 ignored, no upper layer in a router. This step was made for
// routers running in a host
// Step 3
if (this->TTLisZero(p.header.ttlp)) {
// silent discard. Some IP implementations send
// ICMP destination Unreachable-Network message to sender
logger.info("Discard packet: TTL zero for packet with dest_ip: "
+ dest_ip.as_string());
return;
}
// Step 4
p.header.ttlp = this->decreaseTTL(p.header.ttlp);
// Recalculates checksum because the TTL field has being updated
p.header.header_checksum = this->calculateChecksum(p.header);
// Step 5-7
this->routeIPDatagram(p);
}
bool ip_router_protocol::TTLisZero(ushort ttlp) const {
ushort ttl = ttlp >> 8;
std::stringstream stream;
stream << std::hex << ttl;
logger.debug("TTL: " + stream.str());
return ttl == 0;
}
ushort ip_router_protocol::decreaseTTL(ushort ttlp) const {
std::stringstream stream;
stream << std::hex << ttlp;
logger.debug("Before decrease TTL: " + stream.str());
ushort ttl = ttlp >> 8;
--ttl;
ttl = ttl << 8;
ttlp = ttlp & 0x00FF;
ttlp = ttl | ttlp;
stream.str("");
stream << std::hex << ttlp;
logger.debug("After decrease TTL: " + stream.str());
return ttlp;
}