-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.cc
More file actions
70 lines (58 loc) · 2.76 KB
/
router.cc
File metadata and controls
70 lines (58 loc) · 2.76 KB
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
#include "router.hh"
#include "debug.hh"
#include <iostream>
using namespace std;
// route_prefix: The "up-to-32-bit" IPv4 address prefix to match the datagram's destination address against
// prefix_length: For this route to be applicable, how many high-order (most-significant) bits of
// the route_prefix will need to match the corresponding bits of the datagram's destination address?
// next_hop: The IP address of the next hop. Will be empty if the network is directly attached to the router (in
// which case, the next hop address should be the datagram's final destination).
// interface_num: The index of the interface to send the datagram out on.
void Router::add_route( const uint32_t route_prefix,
const uint8_t prefix_length,
const optional<Address> next_hop,
const size_t interface_num )
{
cerr << "DEBUG: adding route " << Address::from_ipv4_numeric( route_prefix ).ip() << "/"
<< static_cast<int>( prefix_length ) << " => " << ( next_hop.has_value() ? next_hop->ip() : "(direct)" )
<< " on interface " << interface_num << "\n";
if ( next_hop.has_value() ) {
route_table_.push_back( { route_prefix, prefix_length, next_hop.value().ipv4_numeric(), interface_num, true} );
} else {
route_table_.push_back( { route_prefix, prefix_length, {}, interface_num, false} );
}
}
// Go through all the interfaces, and route every incoming datagram to its proper outgoing interface.
void Router::route()
{
for ( auto iface : interfaces_ ) {
std::queue<InternetDatagram>& queue = iface->datagrams_received();
while ( !queue.empty() ) {
InternetDatagram dgram = queue.front();
queue.pop();
int longest_prefix_length = -1;
uint8_t select_idx;
for ( uint i = 0 ; i < route_table_.size(); i++ ) {
Route r = route_table_[i];
if ( r.prefix_length > 0 && r.route_prefix >> ( 32 - r.prefix_length ) != dgram.header.dst >> ( 32 - r.prefix_length ) ) {
continue;
}
if ( r.prefix_length > longest_prefix_length ) {
longest_prefix_length = r.prefix_length;
select_idx = i;
}
}
debug("longest_prefix_length is {}, select_idx is {}", longest_prefix_length, select_idx);
if ( longest_prefix_length > -1 && dgram.header.ttl > 1 ) {
dgram.header.ttl -= 1;
dgram.header.compute_checksum();
debug("dgram ttl is {}", dgram.header.ttl);
Address next_hop = Address::from_ipv4_numeric(dgram.header.dst);
if ( route_table_[select_idx].has_next_hop ) {
next_hop = Address::from_ipv4_numeric(route_table_[select_idx].next_hop);
}
interface(route_table_[select_idx].interface_num)->send_datagram(dgram, next_hop);
}
}
}
}