-
Notifications
You must be signed in to change notification settings - Fork 0
/
iprouter.cpp
112 lines (90 loc) · 2.91 KB
/
iprouter.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "iprouter.h"
#include "table.h"
#include <string>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <arpa/inet.h>
#include <stdio.h>
IpRouter::IpRouter(const char* routingFile,
const char* packetsFile,
const char* outFile) :
packetsFile(packetsFile),
outFile(outFile),
routingFile(routingFile)
{
// Open the packet file
packetsFS.open(packetsFile, std::ios::binary);
}
IpRouter::~IpRouter() {
// Delete each dynamically allocated packet.
for (auto it : datagrams) {
delete it;
}
}
Datagram* IpRouter::readPacket() {
// If the file stream is at the end of the file, all packets have been read. Return NULL.
if(packetsFS.peek() == EOF) {
packetsFS.close();
return NULL;
}
// Create a packet on the Heap so it can exist longer than the scope of this function
Datagram* packet = new Datagram;
// Read packet data into object
packet->read(packetsFS);
return packet;
}
void IpRouter::outputError(Datagram packet, std::string error) {
std::cout << "Packet Dropped: " << error << std::endl;
}
void IpRouter::getPackets() {
Datagram* packet;
int counter = 1;
// Read in every packet until the end of the file
while((packet = readPacket())) {
// Check for checksum and TTL errors
if( !packet->compareChecksum() ) {
packet->setError("Checksum is incorrect");
} else if( !packet->decrementTTL()) {
packet->setError("TTL becomes 0");
}
// Set packet number
packet->num = counter;
// Store packet in vector
datagrams.push_back(packet);
++counter;
}
}
void IpRouter::getResults() {
RoutingTable table(routingFile);
table.read();
printf("Packet#\tSource\t\tDestination\tOutcome\n");
for( auto it : datagrams) {
std::string outcome;
// Check if there was an error. If no error, get next hop address
if (it->error) {
outcome = "Packet Dropped: ";
outcome += it->error;
} else {
outcome = "Packet forwarded to ";
outcome += RoutingTable::addr_htos(table.getNextHop(it->destAddress));
}
// Convert Addresses to strings
std::string source = RoutingTable::addr_htos(it->sourceAddress);
std::string dest = RoutingTable::addr_htos(it->destAddress);
// Output formatted string
printf("%d\t%s\t%s\t%s\n", it->num, source.c_str(), dest.c_str(), outcome.c_str());
}
}
void IpRouter::writePackets() {
// Create output filestream
std::ofstream out(outFile, std::ofstream::binary);
// If there is no error, write packet to output file
for(auto it : datagrams) {
if (it->error == NULL)
it->write(&out);
}
out.close();
}