def callback(frame): ''' The action after receiving datagram from link layer. First unpack datagram Case1: if the outside datagram is received by destination end router, it will first do NAT and update datgram, then push upward Case2; if the internal datagram is received by destination, no need for NAT, directly push upward Case3: if this datagram is received in core routers, find the next forwarding hop ip and convert into mac, then send it by linklayer :param frame: received datagram from linklayer :return: None ''' network, transport, action = unpack(frame) if action == ACTION_PUSH: if network.dst_ip == util.get_local_ipv4_address(): IP.push(frame) elif network.dst_ip in forwarding_table: forwarding_ip = forwarding_table[network.dst_ip] if forwarding_ip != WAN_ip: dst_ip = forwarding_ip else: dst_ip = network.dst_ip if dst_ip != forwarding_ip: print('forwaring to', forwarding_table[network.dst_ip]) dst_mac = util.ip2mac(dst_ip) linklayer.sendto(dst_mac, frame) elif (network.dst_ip, transport.dst_port) in NAT_in : network.dst_ip, transport.dst_port = NAT_in[(network.dst_ip, transport.dst_port)] frame = pack(network, transport) IP.push(frame) else: ICMP.host_unreachable(WAN_ip, network.src_ip)
def send(datagram, dst_ip, nat = False): # todo read from file ''' This send method is for both end router and router in core :param datagram: sending content :param dst_ip: destination ip :param nat: a tune to remark current send is for end router or core router :return: None ''' # [for present] import json with open('show.json', 'r') as f: dict_ = json.loads(f.read()) nat = dict_['nat'] if nat == 'True': nat = True elif nat == 'False': nat = False else: raise Exception("Wrong show.json") # [end] if nat: # for end router, do NAT first datagram = NAT(datagram,'out') dst_ip = forwarding_table[dst_ip] linklayer.sendto(util.ip2mac(dst_ip),datagram)
def senddatagram(self, ip_src, ip_dst, ttl, ip_proto, data): datagram = Datagram.pack_datagram(ip_src, ip_dst, ttl, ip_proto, data) ## Here, let's set dst_mac according to our program >>>> dst_mac = util.ip2mac(loadConfig.loadDstIP()) self.sendto(dst_mac, datagram, None) """ how to acquire dst_mac"""
from LinkLayer import LinkLayer, util def callback(frame): print(frame) link = LinkLayer(callback) link.sendto(util.ip2mac("10.20.16.17"), b'hheelekd', None)