-
Notifications
You must be signed in to change notification settings - Fork 0
/
netemulate.py
65 lines (56 loc) · 1.3 KB
/
netemulate.py
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
# Router simulator in a network
# To exercise routing algorithms
#
# Sin-Yaw Wang <swang24@scu.edu
#
import sys
import os
import json
import router
# a nework emulator
class netEmulator:
def __init__(self):
pass
# load the topology from a JSON file
# return None if fail
def rtInit(self, fname):
try:
f=open(fname, 'r')
except:
print('failed to open {}'.format(fname))
return None
try:
net = json.load(f)
except:
print('{} not in JSON format'.format(fname))
return None
f.close()
self.routers=[]
# process the JSON file
# instantiate a "Router" for each one in the JSON file
# add links per topology
# after getting all the routers, initialize the forwarding table
for rtr in net['Network']:
r=router.Router(rtr['Router'])
r.network = self;
for l,c in rtr['Links'].items():
r.addLink(l, c)
self.routers.append(r)
def __str__(self):
return self.__repr__()
# friendly output of router info in JSON syntax
def __repr__(self):
str = '{"Network": ['
for r in net.routers[:-1]:
str += '{},\n'.format(r)
for r in net.routers[-1:]:
str += '{}]'.format(r)
str += '}'
return str;
# test for network initialization
if __name__ == '__main__':
if len(sys.argv) <= 1:
print('need topology file')
net = netEmulator()
net.rtInit(sys.argv[1])
print(net)