write this code to have the same functionality as the second one # #!/usr/bin/python3
import sys
import struct
import wrapper
import threading
import time
from wrapper import recv_from_any_link, send_to_link, get_switch_mac, get_interface_name
def is_unicast(mac):
least = int(mac.split(":")[0], 16)
# if the least significant bit of the first byte is 0, then it is a unicast address
return (least & 0x01) == 0
def send_vlan_packet(interface, data, length, port_vlan, trunk_ports, vlan_id, vlan_id_in):
vlan_out_id = port_vlan.get(interface, -1)
if interface in trunk_ports:
if vlan_id == -1:
data = data[:12] + create_vlan_tag(vlan_id_in) + data[12:]
length = len(data)
send_to_link(interface, length, data)
else: send_to_link(interface, length, data)
elif int(vlan_out_id) == vlan_id_in:
if vlan_id != -1:
data = remove_vlan_tag(data)
length = len(data)
send_to_link(interface, length, data)
else: send_to_link(interface, length, data)
def create_vlan_tag(vlan_id):
tpid = 0x8200
vlan_tci = vlan_id & 0x0FFF
vlan_tag = struct.pack('!HH', tpid, vlan_tci)
return vlan_tag
def remove_vlan_tag(data):
return data[:12] + data[16:]
def get_ports_data(switch_id):
filename = f"configs/switch{switch_id}.cfg"
port_vlan = {}
trunk_ports = set()
try:
with open(filename, "r") as f:
for line in f:
stripped_line = line.strip()
if not stripped_line: # Skip empty lines
continue
parts = stripped_line.split(' ')
if len(parts) < 2: # Ensure there are enough parts
continue
if (len(parts) == 2):
port, vlan_type = parts[0], parts[1]
if vlan_type.strip() == 'T':
trunk_ports.add(port)
else:
port_vlan[port] = int(vlan_type)
except FileNotFoundError:
print(f"File {filename} not found")
return port_vlan, trunk_ports
def parse_ethernet_header(data):
# Unpack the header fields from the byte array
#dest_mac, src_mac, ethertype = struct.unpack('!6s6sH', data[:14])
dest_mac = data[0:6]
src_mac = data[6:12]
# Extract ethertype. Under 802.1Q, this may be the bytes from the VLAN TAG
ether_type = (data[12] << 8) + data[13]
vlan_id = -1
# Check for VLAN tag (0x8100 in network byte order is b'\x81\x00')
if ether_type == 0x8200:
vlan_tci = int.from_bytes(data[14:16], byteorder='big')
vlan_id = vlan_tci & 0x0FFF # extract the 12-bit VLAN ID
ether_type = (data[16] << 8) + data[17]
return dest_mac, src_mac, ether_type, vlan_id
def send_bdpu_every_sec():
while True:
# TODO Send BDPU every second if necessary
time.sleep(1)
def main():
# init returns the max interface number. Our interfaces
# are 0, 1, 2, ..., init_ret value + 1
switch_id = sys.argv[1]
num_interfaces = wrapper.init(sys.argv[2:])
interfaces = range(0, num_interfaces)
MAC_table = {}
port_vlan, trunk_ports = get_ports_data(switch_id)
print("# Starting switch with id {}".format(switch_id), flush=True)
print("[INFO] Switch MAC", ':'.join(f'{b:02x}' for b in get_switch_mac()))
# Create and start a new thread that deals with sending BDPU
t = threading.Thread(target=send_bdpu_every_sec)
t.start()
# Printing interface names
for i in interfaces:
print(get_interface_name(i))
while True:
# Note that data is of type bytes([...]).
# b1 = bytes([72, 101, 108, 108, 111]) # "Hello"
# b2 = bytes([32, 87, 111, 114, 108, 100]) # " World"
# b3 = b1[0:2] + b[3:4].
interface, data, length = recv_from_any_link()
dest_mac, src_mac, ethertype, vlan_id = parse_ethernet_header(data)
# Print the MAC src and MAC dst in human readable format
dest_mac = ':'.join(f'{b:02x}' for b in dest_mac)
src_mac = ':'.join(f'{b:02x}' for b in src_mac)
# Note. Adding a VLAN tag can be as easy as
# tagged_frame = data[0:12] + create_vlan_tag(10) + data[12:]
print(f'Destination MAC: {dest_mac}')
print(f'Source MAC: {src_mac}')
print(f'EtherType: {ethertype}')
print("Received frame of size {} on interface {}".format(length, interface), flush=True)
# TODO: Implement forwarding with learning
MAC_table[src_mac] = interface
if vlan_id != -1:
vlan_id_in = vlan_id
else:
vlan_id_in = port_vlan.get(interface, -1)
if is_unicast(dest_mac):
if dest_mac in MAC_table:
send_vlan_packet(MAC_table[dest_mac], data, length, port_vlan, trunk_ports, vlan_id, vlan_id_in)
else:
for port in interfaces:
if port != interface:
send_vlan_packet(port, data, length, port_vlan, trunk_ports, vlan_id, vlan_id_in)
else:
for port in interfaces:
if port != interface:
send_vlan_packet(port, data, length, port_vlan, trunk_ports, vlan_id, vlan_id_in)
# TODO: Implement VLAN support
# TODO: Implement STP support
# data is of type bytes.
# send_to_link(i, length, data)
if name == "main":
main() the second one: #!/usr/bin/python3
import sys
import struct
import wrapper
import threading
import time
from wrapper import recv_from_any_link, send_to_link, get_switch_mac, get_interface_name
def parse_ethernet_header(data):
# Unpack the header fields from the byte array
# dest_mac, src_mac, ethertype = struct.unpack('!6s6sH', data[:14])
dest_mac = data[0:6]
src_mac = data[6:12]
# Extract ethertype. Under 802.1Q, this may be the bytes from the VLAN TAG
ether_type = (data[12] << 8) + data[13]
vlan_id = -1
# Check for VLAN tag (0x8100 in network byte order is b'\x81\x00')
if ether_type == 0x8200:
vlan_tci = int.from_bytes(data[14:16], byteorder="big")
vlan_id = vlan_tci & 0x0FFF # extract the 12-bit VLAN ID
ether_type = (data[16] << 8) + data[17]
return dest_mac, src_mac, ether_type, vlan_id
def create_vlan_tag(vlan_id):
# 0x8100 for the Ethertype for 802.1Q
# vlan_id & 0x0FFF ensures that only the last 12 bits are used
return struct.pack("!H", 0x8200) + struct.pack("!H", vlan_id & 0x0FFF)
def send_bdpu_every_sec():
while True:
# TODO Send BDPU every second if necessary
time.sleep(1)
def is_unicast(mac):
least = int(mac.split(":")[0], 16)
# if the least significant bit of the first byte is 0, then it is a unicast address
return (least & 0x01) == 0
def parse_config(switch_id: str, interfaces: range):
f_in = open(f"configs/switch{switch_id}.cfg", "r")
priority = int(f_in.readline())
vlans_config = {}
for _ in interfaces:
config = f_in.readline().rstrip("\n").split(" ")
vlans_config[config[0]] = config[1]
f_in.close()
return priority, vlans_config
VLAN support
def send_vlan_packet(interface, data, length, vlan_config, vlan_id, vlan_mod_enter):
vlan_out_id = vlan_config[get_interface_name(interface)]
if vlan_out_id == "T":
# Receieved from an access point
if vlan_id == -1:
data = data[:12] + create_vlan_tag(vlan_mod_enter) + data[12:]
length = len(data)
send_to_link(interface, length, data)
else:
send_to_link(interface, length, data)
elif int(vlan_out_id) == vlan_mod_enter:
# Receieved from an access point
if vlan_id != -1:
send_to_link(interface, len(data[:12] + data[16:]), data[:12] + data[16:])
else:
send_to_link(interface, length, data)
def main():
# init returns the max interface number. Our interfaces
# are 0, 1, 2, ..., init_ret value + 1
switch_id = sys.argv[1]
num_interfaces = wrapper.init(sys.argv[2:])
interfaces = range(0, num_interfaces)
print("# Starting switch with id {}".format(switch_id), flush=True)
print("[INFO] Switch MAC", ':'.join(f'{b:02x}' for b in get_switch_mac()))
CAM_table = {}
prio, vlan_config = parse_config(switch_id, interfaces)
# Printing interface names
for i in interfaces:
name = get_interface_name(i)
# Create and start a new thread that deals with sending BDPU
t = threading.Thread(target=send_bdpu_every_sec)
t.start()
while True:
interface, data, length = recv_from_any_link()
dest_mac, src_mac, ethertype, vlan_id = parse_ethernet_header(data)
# Print the MAC src and MAC dst in human readable format
dest_mac = ":".join(f"{b:02x}" for b in dest_mac)
src_mac = ":".join(f"{b:02x}" for b in src_mac)
print(f"Destination MAC: {dest_mac}")
print(f"Source MAC: {src_mac}")
print(f"EtherType: {ethertype}")
print(f"VLAN ID: {vlan_id}")
print(
"Received frame of size {} on interface {} - {}".format(length, interface, get_interface_name(interface)),
flush=True,
)
# Put the source in the CAM table
CAM_table[src_mac] = interface
# vlan_id_in should always pe populated. Is the id from where the packet was received
vlan_id_in: int = -1
if vlan_id != -1:
vlan_id_in = vlan_id
else:
vlan_id_in = int(vlan_config[get_interface_name(interface)])
# Forwarding with learning
if (is_unicast(dest_mac) and
dest_mac in CAM_table and
CAM_table[dest_mac] in interfaces
):
send_vlan_packet(
CAM_table[dest_mac], data, length, vlan_config, vlan_id, vlan_id_in
)
else:
for i in interfaces:
if i != interface:
send_vlan_packet(
i, data, length, vlan_config, vlan_id, vlan_id_in
)
if name == "main":
main()