TExcelTAD
Home › Computer Networking › Networking Mini Project

Networking Mini Project

In this project you'll build a tiny network simulator in Python, one step at a time. Unlike the toy models in earlier lessons, every message in it is a real byte string: Ethernet frames with a CRC-32 FCS, IPv4 headers with checksums, ARP packets and ICMP messages, all built with struct and checked on arrival. By the end, hosts on two LANs ping each other across two routers, and you'll write your own traceroute.

The finished network:

text
H1 192.168.1.10    H2 192.168.1.20
          \          /
              SW1            LAN A 192.168.1.0/24
               |
        g0 192.168.1.1
              R1
        g1 10.0.12.1
               |
              SW2            link 10.0.12.0/30
               |
        g1 10.0.12.2
              R2
        g0 172.16.5.1
               |
              SW3            LAN B 172.16.5.0/24
          /          \
H3 172.16.5.30     H4 172.16.5.40

It brings together most of the course: encapsulation, Ethernet and the FCS, MAC learning, ARP, IPv4 headers and checksums, subnets, routing tables with longest-prefix match, TTL and ICMP.

Step 1: Wire formats

First, the functions that turn fields into bytes and back. They're the same formats you built in the Ethernet, IPv4 and ICMP lessons, now gathered in one place. The test at the bottom builds a ping, wraps it in a packet and a frame, dumps the bytes and parses them back.

python · try it yourself
import ipaddress
import struct
import zlib

def checksum(data):
    if len(data) % 2:
        data += b"\0"
    total = sum(struct.unpack(f"!{len(data) // 2}H", data))
    while total >> 16:
        total = (total & 0xFFFF) + (total >> 16)
    return ~total & 0xFFFF

def mac_bytes(mac):
    return bytes.fromhex(mac.replace(":", ""))

def build_frame(dst, src, ethertype, payload):
    payload = payload.ljust(46, b"\0")                      # minimum payload size
    body = struct.pack("!6s6sH", mac_bytes(dst), mac_bytes(src), ethertype) + payload
    return body + struct.pack("<I", zlib.crc32(body))       # FCS

def parse_frame(frame):
    if zlib.crc32(frame) != 0x2144DF1C:                     # CRC residue check
        raise ValueError("bad FCS")
    dst, src, ethertype = struct.unpack("!6s6sH", frame[:14])
    return dst.hex(":"), src.hex(":"), ethertype, frame[14:-4]

def build_ipv4(src, dst, ttl, proto, payload, ident=1):
    header = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(payload), ident, 0x4000, ttl, proto, 0,
                         ipaddress.IPv4Address(src).packed, ipaddress.IPv4Address(dst).packed)
    header = header[:10] + struct.pack("!H", checksum(header)) + header[12:]
    return header + payload

def parse_ipv4(data):
    if checksum(data[:20]) != 0:
        raise ValueError("bad IP checksum")
    total, ident, ttl, proto = struct.unpack("!2xHH2xBB", data[:10])
    src, dst = (str(ipaddress.IPv4Address(data[i:i + 4])) for i in (12, 16))
    return {"src": src, "dst": dst, "ttl": ttl, "proto": proto, "id": ident, "payload": data[20:total]}

def build_icmp(icmp_type, ident, seq, data=b""):
    body = struct.pack("!BBHHH", icmp_type, 0, 0, ident, seq) + data
    return body[:2] + struct.pack("!H", checksum(body)) + body[4:]

icmp = build_icmp(8, 0x1234, 1, b"ping")
packet = build_ipv4("192.168.1.10", "172.16.5.30", 64, 1, icmp)
frame = build_frame("02:00:00:00:01:00", "02:00:00:00:00:01", 0x0800, packet)

print(len(icmp), "byte ICMP message in a", len(packet), "byte packet in a", len(frame), "byte frame")
for offset in range(0, len(frame), 16):
    print(f"  {offset:04x}  {frame[offset:offset + 16].hex(' ')}")

dst, src, ethertype, payload = parse_frame(frame)
info = parse_ipv4(payload)
print(f"frame  {src} -> {dst} type 0x{ethertype:04x}")
print(f"packet {info['src']} -> {info['dst']} ttl {info['ttl']} proto {info['proto']}")
print(f"icmp   type {info['payload'][0]} checksum ok: {checksum(info['payload']) == 0}")

damaged = bytearray(frame)
damaged[30] ^= 0x01
try:
    parse_frame(bytes(damaged))
except ValueError as err:
    print("damaged frame:", err)
12 byte ICMP message in a 32 byte packet in a 64 byte frame
  0000  02 00 00 00 01 00 02 00 00 00 00 01 08 00 45 00
  0010  00 20 00 01 40 00 40 01 c7 fb c0 a8 01 0a ac 10
  0020  05 1e 08 00 06 fa 12 34 00 01 70 69 6e 67 00 00
  0030  00 00 00 00 00 00 00 00 00 00 00 00 45 83 4e 77
frame  02:00:00:00:00:01 -> 02:00:00:00:01:00 type 0x0800
packet 192.168.1.10 -> 172.16.5.30 ttl 64 proto 1
icmp   type 8 checksum ok: True
damaged frame: bad FCS

The 12-byte ICMP message sits in a 32-byte IPv4 packet, which is padded to a 64-byte frame (Ethernet's minimum). Flipping one bit makes the receiver reject the frame, just like a real NIC.

Step 2: One LAN: hosts, a switch and ARP

Now some devices. An Interface has a MAC and an IP address and is plugged into a Switch port. The switch learns source MACs and floods or forwards, exactly as in the switching lesson. A Host resolves IP addresses with real ARP requests and answers pings.

Delivery is synchronous: send() calls the switch, which calls the receiving device, which may reply straight away. That's why H3's reaction to the ARP broadcast shows up after H2's whole reply: events are processed depth-first.

python · try it yourself
import ipaddress
import struct
import zlib

def checksum(data):
    if len(data) % 2:
        data += b"\0"
    total = sum(struct.unpack(f"!{len(data) // 2}H", data))
    while total >> 16:
        total = (total & 0xFFFF) + (total >> 16)
    return ~total & 0xFFFF

def mac_bytes(mac):
    return bytes.fromhex(mac.replace(":", ""))

def build_frame(dst, src, ethertype, payload):
    payload = payload.ljust(46, b"\0")                      # minimum payload size
    body = struct.pack("!6s6sH", mac_bytes(dst), mac_bytes(src), ethertype) + payload
    return body + struct.pack("<I", zlib.crc32(body))       # FCS

def parse_frame(frame):
    if zlib.crc32(frame) != 0x2144DF1C:                     # CRC residue check
        raise ValueError("bad FCS")
    dst, src, ethertype = struct.unpack("!6s6sH", frame[:14])
    return dst.hex(":"), src.hex(":"), ethertype, frame[14:-4]

def build_ipv4(src, dst, ttl, proto, payload, ident=1):
    header = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(payload), ident, 0x4000, ttl, proto, 0,
                         ipaddress.IPv4Address(src).packed, ipaddress.IPv4Address(dst).packed)
    header = header[:10] + struct.pack("!H", checksum(header)) + header[12:]
    return header + payload

def parse_ipv4(data):
    if checksum(data[:20]) != 0:
        raise ValueError("bad IP checksum")
    total, ident, ttl, proto = struct.unpack("!2xHH2xBB", data[:10])
    src, dst = (str(ipaddress.IPv4Address(data[i:i + 4])) for i in (12, 16))
    return {"src": src, "dst": dst, "ttl": ttl, "proto": proto, "id": ident, "payload": data[20:total]}

def build_icmp(icmp_type, ident, seq, data=b""):
    body = struct.pack("!BBHHH", icmp_type, 0, 0, ident, seq) + data
    return body[:2] + struct.pack("!H", checksum(body)) + body[4:]

def build_arp(op, smac, sip, tmac, tip):
    return struct.pack("!HHBBH6s4s6s4s", 1, 0x0800, 6, 4, op, mac_bytes(smac),
                       ipaddress.IPv4Address(sip).packed, mac_bytes(tmac), ipaddress.IPv4Address(tip).packed)

def parse_arp(data):
    op, smac, sip, tmac, tip = struct.unpack("!6xH6s4s6s4s", data[:28])
    return op, smac.hex(":"), str(ipaddress.IPv4Address(sip)), str(ipaddress.IPv4Address(tip))

BROADCAST = "ff:ff:ff:ff:ff:ff"

class Switch:
    def __init__(self, name):
        self.name, self.ports, self.table = name, {}, {}

    def plug(self, iface):
        port = len(self.ports) + 1
        self.ports[port] = iface
        iface.switch, iface.port = self, port

    def receive(self, in_port, frame):
        dst, src, _, _ = parse_frame(frame)
        self.table[src] = in_port                                   # learn
        if dst in self.table:
            outs = [self.table[dst]]
            print(f"    {self.name}: {src[-2:]} -> {dst[-2:]} forward to port {outs[0]}")
        else:
            outs = [p for p in self.ports if p != in_port]
            print(f"    {self.name}: {src[-2:]} -> {dst[-2:]} flood to ports {outs}")
        for p in outs:
            self.ports[p].device.receive(self.ports[p], frame)

class Interface:
    def __init__(self, device, mac, cidr):
        self.device, self.mac = device, mac
        self.ip = ipaddress.ip_interface(cidr)
        self.arp = {}

    def send(self, dst_mac, ethertype, payload):
        self.switch.receive(self.port, build_frame(dst_mac, self.mac, ethertype, payload))

class Host:
    def __init__(self, name, mac, cidr):
        self.name = name
        self.iface = Interface(self, mac, cidr)

    def resolve(self, ip):
        if ip in self.iface.arp:
            print(f"  {self.name}: ARP cache hit {ip} is {self.iface.arp[ip]}")
        else:
            print(f"  {self.name}: ARP who-has {ip}?")
            self.iface.send(BROADCAST, 0x0806,
                            build_arp(1, self.iface.mac, str(self.iface.ip.ip), "00:00:00:00:00:00", ip))
        return self.iface.arp.get(ip)

    def ping(self, dst, seq):
        src = str(self.iface.ip.ip)
        if ipaddress.ip_address(dst) not in self.iface.ip.network:
            print(f"  {self.name}: {dst} is not on my LAN and I have no router yet")
            return
        mac = self.resolve(dst)
        print(f"  {self.name}: echo request seq={seq} to {dst}")
        self.iface.send(mac, 0x0800, build_ipv4(src, dst, 64, 1, build_icmp(8, 0x1234, seq, b"ping")))

    def receive(self, iface, frame):
        dst, src, ethertype, payload = parse_frame(frame)
        if dst not in (iface.mac, BROADCAST):
            return
        if ethertype == 0x0806:
            op, smac, sip, tip = parse_arp(payload)
            if tip != str(iface.ip.ip):
                print(f"  {self.name}: ignores ARP for {tip}")
                return
            iface.arp[sip] = smac
            if op == 1:
                print(f"  {self.name}: ARP reply {tip} is at {iface.mac}")
                iface.send(smac, 0x0806, build_arp(2, iface.mac, tip, smac, sip))
        elif ethertype == 0x0800:
            info = parse_ipv4(payload)
            icmp_type, = struct.unpack("!B", info["payload"][:1])
            ident, seq = struct.unpack("!HH", info["payload"][4:8])
            if icmp_type == 8:
                print(f"  {self.name}: echo request from {info['src']}, replying")
                reply = build_icmp(0, ident, seq, info["payload"][8:])
                iface.send(src, 0x0800, build_ipv4(info["dst"], info["src"], 64, 1, reply))
            else:
                print(f"  {self.name}: echo reply seq={seq} from {info['src']}")

sw = Switch("SW1")
h1 = Host("H1", "02:00:00:00:00:01", "192.168.1.10/24")
h2 = Host("H2", "02:00:00:00:00:02", "192.168.1.20/24")
h3 = Host("H3", "02:00:00:00:00:03", "192.168.1.30/24")
for host in (h1, h2, h3):
    sw.plug(host.iface)

print("H1 pings H2 (first time)")
h1.ping("192.168.1.20", seq=1)
print("H1 pings H2 again")
h1.ping("192.168.1.20", seq=2)
print("H1 pings 172.16.5.30")
h1.ping("172.16.5.30", seq=3)
print("SW1 table:", sw.table)
H1 pings H2 (first time)
  H1: ARP who-has 192.168.1.20?
    SW1: 01 -> ff flood to ports [2, 3]
  H2: ARP reply 192.168.1.20 is at 02:00:00:00:00:02
    SW1: 02 -> 01 forward to port 1
  H3: ignores ARP for 192.168.1.20
  H1: echo request seq=1 to 192.168.1.20
    SW1: 01 -> 02 forward to port 2
  H2: echo request from 192.168.1.10, replying
    SW1: 02 -> 01 forward to port 1
  H1: echo reply seq=1 from 192.168.1.20
H1 pings H2 again
  H1: ARP cache hit 192.168.1.20 is 02:00:00:00:00:02
  H1: echo request seq=2 to 192.168.1.20
    SW1: 01 -> 02 forward to port 2
  H2: echo request from 192.168.1.10, replying
    SW1: 02 -> 01 forward to port 1
  H1: echo reply seq=2 from 192.168.1.20
H1 pings 172.16.5.30
  H1: 172.16.5.30 is not on my LAN and I have no router yet
SW1 table: {'02:00:00:00:00:01': 1, '02:00:00:00:00:02': 2}

Read the trace carefully: the first ping needs an ARP broadcast (flooded to every port), the reply is unicast, and from then on the switch forwards frames only where they need to go. The second ping skips ARP entirely thanks to the cache. And without a router, H1 can't reach anything outside its own /24.

Step 3: Routers and routing tables

To leave the LAN we need routers. The code is reorganised around a Device base class with a list of interfaces and a routing table:

  • add_iface adds an interface and its connected route automatically;
  • add_route adds a static route through a next-hop router;
  • lookup does longest-prefix match;
  • send_ip picks a route, ARPs for the next hop (the destination itself on a connected network, otherwise the router) and sends the frame.

A Host is a device with one interface and a default route to its gateway. A Router forwards packets that aren't addressed to it: it decrements the TTL (rebuilding the header, so the checksum is recomputed), and sends ICMP errors back when the TTL runs out or there's no route. Each device prints one line per packet it sends, so you can follow every hop.

python · try it yourself
import ipaddress
import struct
import zlib

# ---------- wire formats ----------
def checksum(data):
    if len(data) % 2:
        data += b"\0"
    total = sum(struct.unpack(f"!{len(data) // 2}H", data))
    while total >> 16:
        total = (total & 0xFFFF) + (total >> 16)
    return ~total & 0xFFFF

def mac_bytes(mac):
    return bytes.fromhex(mac.replace(":", ""))

def build_frame(dst, src, ethertype, payload):
    payload = payload.ljust(46, b"\0")
    body = struct.pack("!6s6sH", mac_bytes(dst), mac_bytes(src), ethertype) + payload
    return body + struct.pack("<I", zlib.crc32(body))

def parse_frame(frame):
    if zlib.crc32(frame) != 0x2144DF1C:
        raise ValueError("bad FCS")
    dst, src, ethertype = struct.unpack("!6s6sH", frame[:14])
    return dst.hex(":"), src.hex(":"), ethertype, frame[14:-4]

def build_ipv4(src, dst, ttl, proto, payload, ident=1):
    header = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(payload), ident, 0x4000, ttl, proto, 0,
                         ipaddress.IPv4Address(src).packed, ipaddress.IPv4Address(dst).packed)
    header = header[:10] + struct.pack("!H", checksum(header)) + header[12:]
    return header + payload

def parse_ipv4(data):
    if checksum(data[:20]) != 0:
        raise ValueError("bad IP checksum")
    total, ident, ttl, proto = struct.unpack("!2xHH2xBB", data[:10])
    src, dst = (str(ipaddress.IPv4Address(data[i:i + 4])) for i in (12, 16))
    return {"src": src, "dst": dst, "ttl": ttl, "proto": proto, "id": ident, "payload": data[20:total]}

def build_icmp(icmp_type, ident, seq, data=b""):
    body = struct.pack("!BBHHH", icmp_type, 0, 0, ident, seq) + data
    return body[:2] + struct.pack("!H", checksum(body)) + body[4:]

def build_arp(op, smac, sip, tmac, tip):
    return struct.pack("!HHBBH6s4s6s4s", 1, 0x0800, 6, 4, op, mac_bytes(smac),
                       ipaddress.IPv4Address(sip).packed, mac_bytes(tmac), ipaddress.IPv4Address(tip).packed)

def parse_arp(data):
    op, smac, sip, tmac, tip = struct.unpack("!6xH6s4s6s4s", data[:28])
    return op, smac.hex(":"), str(ipaddress.IPv4Address(sip)), str(ipaddress.IPv4Address(tip))

BROADCAST = "ff:ff:ff:ff:ff:ff"
VERBOSE = True

def say(text):
    if VERBOSE:
        print(text)

ICMP_NAMES = {0: "echo reply", 8: "echo request", 11: "time exceeded", 3: "unreachable"}

# ---------- devices ----------
class Switch:
    def __init__(self, name):
        self.name, self.ports, self.table = name, {}, {}

    def plug(self, iface):
        port = len(self.ports) + 1
        self.ports[port] = iface
        iface.switch, iface.port = self, port

    def receive(self, in_port, frame):
        dst, src, _, _ = parse_frame(frame)
        self.table[src] = in_port
        if dst in self.table:
            outs = [self.table[dst]]
        else:
            outs = [p for p in self.ports if p != in_port]
        for p in outs:
            self.ports[p].device.receive(self.ports[p], frame)

class Interface:
    def __init__(self, device, name, mac, cidr):
        self.device, self.name, self.mac = device, name, mac
        self.ip = ipaddress.ip_interface(cidr)
        self.arp = {}

    def send(self, dst_mac, ethertype, payload):
        self.switch.receive(self.port, build_frame(dst_mac, self.mac, ethertype, payload))

class Device:
    def __init__(self, name):
        self.name, self.ifaces, self.routes, self.log = name, [], [], []

    def add_iface(self, name, mac, cidr):
        iface = Interface(self, name, mac, cidr)
        self.ifaces.append(iface)
        self.routes.append((iface.ip.network, None, iface))       # connected route
        return iface

    def add_route(self, prefix, via):
        out = next(i for i in self.ifaces if ipaddress.ip_address(via) in i.ip.network)
        self.routes.append((ipaddress.ip_network(prefix), via, out))

    def lookup(self, dst):
        ip = ipaddress.ip_address(dst)
        matches = [r for r in self.routes if ip in r[0]]
        return max(matches, key=lambda r: r[0].prefixlen) if matches else None

    def resolve(self, iface, ip):
        if ip not in iface.arp:
            iface.send(BROADCAST, 0x0806, build_arp(1, iface.mac, str(iface.ip.ip), "00:00:00:00:00:00", ip))
        return iface.arp.get(ip)

    def send_ip(self, packet):
        info = parse_ipv4(packet)
        route = self.lookup(info["dst"])
        if route is None:
            say(f"  {self.name}: no route to {info['dst']}")
            return
        net, via, out = route
        next_hop = via or info["dst"]
        mac = self.resolve(out, next_hop)
        say(f"  {self.name}: {info['src']} -> {info['dst']} ttl={info['ttl']} "
              f"via {out.name} to {next_hop} ({mac})")
        out.send(mac, 0x0800, packet)

    def receive(self, iface, frame):
        dst, src, ethertype, payload = parse_frame(frame)
        if dst not in (iface.mac, BROADCAST):
            return                                                # not for us
        if ethertype == 0x0806:
            op, smac, sip, tip = parse_arp(payload)
            iface.arp[sip] = smac
            if op == 1 and tip == str(iface.ip.ip):
                iface.send(smac, 0x0806, build_arp(2, iface.mac, tip, smac, sip))
        elif ethertype == 0x0800:
            self.handle_ip(iface, payload)

    def my_ips(self):
        return {str(i.ip.ip) for i in self.ifaces}

    def handle_ip(self, iface, packet):
        info = parse_ipv4(packet)
        if info["dst"] in self.my_ips():
            self.deliver(info)
        else:
            self.forward(iface, info)

    def deliver(self, info):
        icmp_type, = struct.unpack("!B", info["payload"][:1])
        ident, seq = struct.unpack("!HH", info["payload"][4:8])
        say(f"  {self.name}: got ICMP {ICMP_NAMES[icmp_type]} from {info['src']} (ttl {info['ttl']})")
        self.log.append((icmp_type, info["src"]))
        if icmp_type == 8:
            reply = build_icmp(0, ident, seq, info["payload"][8:])
            self.send_ip(build_ipv4(info["dst"], info["src"], 64, 1, reply))

    def forward(self, iface, info):
        say(f"  {self.name}: drops packet for {info['dst']} (not a router)")

class Host(Device):
    def __init__(self, name, mac, cidr, gateway):
        super().__init__(name)
        self.add_iface("eth0", mac, cidr)
        self.routes.append((ipaddress.ip_network("0.0.0.0/0"), gateway, self.ifaces[0]))

    def ping(self, dst, seq=1, ttl=64):
        src = str(self.ifaces[0].ip.ip)
        self.send_ip(build_ipv4(src, dst, ttl, 1, build_icmp(8, 0x1234, seq, b"ping")))

class Router(Device):
    def error(self, iface, info, icmp_type, reason):
        say(f"  {self.name}: {reason}, sending ICMP {ICMP_NAMES[icmp_type]} to {info['src']}")
        original = build_ipv4(info["src"], info["dst"], info["ttl"], info["proto"], info["payload"])
        icmp = build_icmp(icmp_type, 0, 0, original[:28])      # quote the start of the bad packet
        self.send_ip(build_ipv4(str(iface.ip.ip), info["src"], 64, 1, icmp))

    def forward(self, iface, info):
        if info["ttl"] <= 1:
            return self.error(iface, info, 11, f"TTL expired for {info['dst']}")
        if self.lookup(info["dst"]) is None:
            return self.error(iface, info, 3, f"no route to {info['dst']}")
        packet = build_ipv4(info["src"], info["dst"], info["ttl"] - 1, info["proto"], info["payload"], info["id"])
        self.send_ip(packet)

# ---------- topology ----------
#  H1 ---\                        /--- H3
#         SW1 --- R1 ===== R2 --- SW3
#  H2 ---/       (10.0.12.0/30)    \--- H4
lan_a, link, lan_b = Switch("SW1"), Switch("SW2"), Switch("SW3")

h1 = Host("H1", "02:00:00:00:00:01", "192.168.1.10/24", "192.168.1.1")
h2 = Host("H2", "02:00:00:00:00:02", "192.168.1.20/24", "192.168.1.1")
h3 = Host("H3", "02:00:00:00:00:03", "172.16.5.30/24", "172.16.5.1")
h4 = Host("H4", "02:00:00:00:00:04", "172.16.5.40/24", "172.16.5.1")

r1 = Router("R1")
r2 = Router("R2")
for switch, iface in [(lan_a, h1.ifaces[0]), (lan_a, h2.ifaces[0]),
                      (lan_a, r1.add_iface("g0", "02:00:00:00:01:00", "192.168.1.1/24")),
                      (link, r1.add_iface("g1", "02:00:00:00:01:01", "10.0.12.1/30")),
                      (link, r2.add_iface("g1", "02:00:00:00:02:01", "10.0.12.2/30")),
                      (lan_b, r2.add_iface("g0", "02:00:00:00:02:00", "172.16.5.1/24")),
                      (lan_b, h3.ifaces[0]), (lan_b, h4.ifaces[0])]:
    switch.plug(iface)
r1.add_route("172.16.0.0/16", via="10.0.12.2")
r2.add_route("192.168.1.0/24", via="10.0.12.1")

print("1) H1 pings H2 (same LAN)")
h1.ping("192.168.1.20")
print("2) H1 pings H3 (across two routers)")
h1.ping("172.16.5.30", seq=2)
print("3) H1 pings H4 with TTL 2")
h1.ping("172.16.5.40", seq=3, ttl=2)
print("4) H2 pings 8.8.8.8")
h2.ping("8.8.8.8", seq=4)
print("MAC table of SW1:", lan_a.table)
print("ARP cache of R1 g1:", r1.ifaces[1].arp)
1) H1 pings H2 (same LAN)
  H1: 192.168.1.10 -> 192.168.1.20 ttl=64 via eth0 to 192.168.1.20 (02:00:00:00:00:02)
  H2: got ICMP echo request from 192.168.1.10 (ttl 64)
  H2: 192.168.1.20 -> 192.168.1.10 ttl=64 via eth0 to 192.168.1.10 (02:00:00:00:00:01)
  H1: got ICMP echo reply from 192.168.1.20 (ttl 64)
2) H1 pings H3 (across two routers)
  H1: 192.168.1.10 -> 172.16.5.30 ttl=64 via eth0 to 192.168.1.1 (02:00:00:00:01:00)
  R1: 192.168.1.10 -> 172.16.5.30 ttl=63 via g1 to 10.0.12.2 (02:00:00:00:02:01)
  R2: 192.168.1.10 -> 172.16.5.30 ttl=62 via g0 to 172.16.5.30 (02:00:00:00:00:03)
  H3: got ICMP echo request from 192.168.1.10 (ttl 62)
  H3: 172.16.5.30 -> 192.168.1.10 ttl=64 via eth0 to 172.16.5.1 (02:00:00:00:02:00)
  R2: 172.16.5.30 -> 192.168.1.10 ttl=63 via g1 to 10.0.12.1 (02:00:00:00:01:01)
  R1: 172.16.5.30 -> 192.168.1.10 ttl=62 via g0 to 192.168.1.10 (02:00:00:00:00:01)
  H1: got ICMP echo reply from 172.16.5.30 (ttl 62)
3) H1 pings H4 with TTL 2
  H1: 192.168.1.10 -> 172.16.5.40 ttl=2 via eth0 to 192.168.1.1 (02:00:00:00:01:00)
  R1: 192.168.1.10 -> 172.16.5.40 ttl=1 via g1 to 10.0.12.2 (02:00:00:00:02:01)
  R2: TTL expired for 172.16.5.40, sending ICMP time exceeded to 192.168.1.10
  R2: 10.0.12.2 -> 192.168.1.10 ttl=64 via g1 to 10.0.12.1 (02:00:00:00:01:01)
  R1: 10.0.12.2 -> 192.168.1.10 ttl=63 via g0 to 192.168.1.10 (02:00:00:00:00:01)
  H1: got ICMP time exceeded from 10.0.12.2 (ttl 63)
4) H2 pings 8.8.8.8
  H2: 192.168.1.20 -> 8.8.8.8 ttl=64 via eth0 to 192.168.1.1 (02:00:00:00:01:00)
  R1: no route to 8.8.8.8, sending ICMP unreachable to 192.168.1.20
  R1: 192.168.1.1 -> 192.168.1.20 ttl=64 via g0 to 192.168.1.20 (02:00:00:00:00:02)
  H2: got ICMP unreachable from 192.168.1.1 (ttl 64)
MAC table of SW1: {'02:00:00:00:00:01': 1, '02:00:00:00:00:02': 2, '02:00:00:00:01:00': 3}
ARP cache of R1 g1: {'10.0.12.2': '02:00:00:00:02:01'}

Things to notice:

  • In ping 2 the IP addresses never change end to end, but each hop sends the frame to a different MAC (the next router's interface), and the TTL drops by one per router: H3 receives TTL 62.
  • In ping 3 the TTL reaches its limit at R2, which reports time exceeded from its own address, 10.0.12.2.
  • In ping 4, R1 has no route for 8.8.8.8 (we never gave it a default route) and answers unreachable.
  • R1 learned R2's MAC through ARP on the 10.0.12.0/30 link, and SW1 learned the three MACs on LAN A.

Step 4: Your own traceroute

Traceroute is now just a loop: send pings with TTL 1, 2, 3, … and report who answered each one. A global VERBOSE switch silences the per-hop logging so only the summary is printed.

python · try it yourself
import ipaddress
import struct
import zlib

# ---------- wire formats ----------
def checksum(data):
    if len(data) % 2:
        data += b"\0"
    total = sum(struct.unpack(f"!{len(data) // 2}H", data))
    while total >> 16:
        total = (total & 0xFFFF) + (total >> 16)
    return ~total & 0xFFFF

def mac_bytes(mac):
    return bytes.fromhex(mac.replace(":", ""))

def build_frame(dst, src, ethertype, payload):
    payload = payload.ljust(46, b"\0")
    body = struct.pack("!6s6sH", mac_bytes(dst), mac_bytes(src), ethertype) + payload
    return body + struct.pack("<I", zlib.crc32(body))

def parse_frame(frame):
    if zlib.crc32(frame) != 0x2144DF1C:
        raise ValueError("bad FCS")
    dst, src, ethertype = struct.unpack("!6s6sH", frame[:14])
    return dst.hex(":"), src.hex(":"), ethertype, frame[14:-4]

def build_ipv4(src, dst, ttl, proto, payload, ident=1):
    header = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(payload), ident, 0x4000, ttl, proto, 0,
                         ipaddress.IPv4Address(src).packed, ipaddress.IPv4Address(dst).packed)
    header = header[:10] + struct.pack("!H", checksum(header)) + header[12:]
    return header + payload

def parse_ipv4(data):
    if checksum(data[:20]) != 0:
        raise ValueError("bad IP checksum")
    total, ident, ttl, proto = struct.unpack("!2xHH2xBB", data[:10])
    src, dst = (str(ipaddress.IPv4Address(data[i:i + 4])) for i in (12, 16))
    return {"src": src, "dst": dst, "ttl": ttl, "proto": proto, "id": ident, "payload": data[20:total]}

def build_icmp(icmp_type, ident, seq, data=b""):
    body = struct.pack("!BBHHH", icmp_type, 0, 0, ident, seq) + data
    return body[:2] + struct.pack("!H", checksum(body)) + body[4:]

def build_arp(op, smac, sip, tmac, tip):
    return struct.pack("!HHBBH6s4s6s4s", 1, 0x0800, 6, 4, op, mac_bytes(smac),
                       ipaddress.IPv4Address(sip).packed, mac_bytes(tmac), ipaddress.IPv4Address(tip).packed)

def parse_arp(data):
    op, smac, sip, tmac, tip = struct.unpack("!6xH6s4s6s4s", data[:28])
    return op, smac.hex(":"), str(ipaddress.IPv4Address(sip)), str(ipaddress.IPv4Address(tip))

BROADCAST = "ff:ff:ff:ff:ff:ff"
VERBOSE = True

def say(text):
    if VERBOSE:
        print(text)

ICMP_NAMES = {0: "echo reply", 8: "echo request", 11: "time exceeded", 3: "unreachable"}

# ---------- devices ----------
class Switch:
    def __init__(self, name):
        self.name, self.ports, self.table = name, {}, {}

    def plug(self, iface):
        port = len(self.ports) + 1
        self.ports[port] = iface
        iface.switch, iface.port = self, port

    def receive(self, in_port, frame):
        dst, src, _, _ = parse_frame(frame)
        self.table[src] = in_port
        if dst in self.table:
            outs = [self.table[dst]]
        else:
            outs = [p for p in self.ports if p != in_port]
        for p in outs:
            self.ports[p].device.receive(self.ports[p], frame)

class Interface:
    def __init__(self, device, name, mac, cidr):
        self.device, self.name, self.mac = device, name, mac
        self.ip = ipaddress.ip_interface(cidr)
        self.arp = {}

    def send(self, dst_mac, ethertype, payload):
        self.switch.receive(self.port, build_frame(dst_mac, self.mac, ethertype, payload))

class Device:
    def __init__(self, name):
        self.name, self.ifaces, self.routes, self.log = name, [], [], []

    def add_iface(self, name, mac, cidr):
        iface = Interface(self, name, mac, cidr)
        self.ifaces.append(iface)
        self.routes.append((iface.ip.network, None, iface))       # connected route
        return iface

    def add_route(self, prefix, via):
        out = next(i for i in self.ifaces if ipaddress.ip_address(via) in i.ip.network)
        self.routes.append((ipaddress.ip_network(prefix), via, out))

    def lookup(self, dst):
        ip = ipaddress.ip_address(dst)
        matches = [r for r in self.routes if ip in r[0]]
        return max(matches, key=lambda r: r[0].prefixlen) if matches else None

    def resolve(self, iface, ip):
        if ip not in iface.arp:
            iface.send(BROADCAST, 0x0806, build_arp(1, iface.mac, str(iface.ip.ip), "00:00:00:00:00:00", ip))
        return iface.arp.get(ip)

    def send_ip(self, packet):
        info = parse_ipv4(packet)
        route = self.lookup(info["dst"])
        if route is None:
            say(f"  {self.name}: no route to {info['dst']}")
            return
        net, via, out = route
        next_hop = via or info["dst"]
        mac = self.resolve(out, next_hop)
        say(f"  {self.name}: {info['src']} -> {info['dst']} ttl={info['ttl']} "
              f"via {out.name} to {next_hop} ({mac})")
        out.send(mac, 0x0800, packet)

    def receive(self, iface, frame):
        dst, src, ethertype, payload = parse_frame(frame)
        if dst not in (iface.mac, BROADCAST):
            return                                                # not for us
        if ethertype == 0x0806:
            op, smac, sip, tip = parse_arp(payload)
            iface.arp[sip] = smac
            if op == 1 and tip == str(iface.ip.ip):
                iface.send(smac, 0x0806, build_arp(2, iface.mac, tip, smac, sip))
        elif ethertype == 0x0800:
            self.handle_ip(iface, payload)

    def my_ips(self):
        return {str(i.ip.ip) for i in self.ifaces}

    def handle_ip(self, iface, packet):
        info = parse_ipv4(packet)
        if info["dst"] in self.my_ips():
            self.deliver(info)
        else:
            self.forward(iface, info)

    def deliver(self, info):
        icmp_type, = struct.unpack("!B", info["payload"][:1])
        ident, seq = struct.unpack("!HH", info["payload"][4:8])
        say(f"  {self.name}: got ICMP {ICMP_NAMES[icmp_type]} from {info['src']} (ttl {info['ttl']})")
        self.log.append((icmp_type, info["src"]))
        if icmp_type == 8:
            reply = build_icmp(0, ident, seq, info["payload"][8:])
            self.send_ip(build_ipv4(info["dst"], info["src"], 64, 1, reply))

    def forward(self, iface, info):
        say(f"  {self.name}: drops packet for {info['dst']} (not a router)")

class Host(Device):
    def __init__(self, name, mac, cidr, gateway):
        super().__init__(name)
        self.add_iface("eth0", mac, cidr)
        self.routes.append((ipaddress.ip_network("0.0.0.0/0"), gateway, self.ifaces[0]))

    def ping(self, dst, seq=1, ttl=64):
        src = str(self.ifaces[0].ip.ip)
        self.send_ip(build_ipv4(src, dst, ttl, 1, build_icmp(8, 0x1234, seq, b"ping")))

class Router(Device):
    def error(self, iface, info, icmp_type, reason):
        say(f"  {self.name}: {reason}, sending ICMP {ICMP_NAMES[icmp_type]} to {info['src']}")
        original = build_ipv4(info["src"], info["dst"], info["ttl"], info["proto"], info["payload"])
        icmp = build_icmp(icmp_type, 0, 0, original[:28])      # quote the start of the bad packet
        self.send_ip(build_ipv4(str(iface.ip.ip), info["src"], 64, 1, icmp))

    def forward(self, iface, info):
        if info["ttl"] <= 1:
            return self.error(iface, info, 11, f"TTL expired for {info['dst']}")
        if self.lookup(info["dst"]) is None:
            return self.error(iface, info, 3, f"no route to {info['dst']}")
        packet = build_ipv4(info["src"], info["dst"], info["ttl"] - 1, info["proto"], info["payload"], info["id"])
        self.send_ip(packet)

# ---------- topology ----------
#  H1 ---\                        /--- H3
#         SW1 --- R1 ===== R2 --- SW3
#  H2 ---/       (10.0.12.0/30)    \--- H4
lan_a, link, lan_b = Switch("SW1"), Switch("SW2"), Switch("SW3")

h1 = Host("H1", "02:00:00:00:00:01", "192.168.1.10/24", "192.168.1.1")
h2 = Host("H2", "02:00:00:00:00:02", "192.168.1.20/24", "192.168.1.1")
h3 = Host("H3", "02:00:00:00:00:03", "172.16.5.30/24", "172.16.5.1")
h4 = Host("H4", "02:00:00:00:00:04", "172.16.5.40/24", "172.16.5.1")

r1 = Router("R1")
r2 = Router("R2")
for switch, iface in [(lan_a, h1.ifaces[0]), (lan_a, h2.ifaces[0]),
                      (lan_a, r1.add_iface("g0", "02:00:00:00:01:00", "192.168.1.1/24")),
                      (link, r1.add_iface("g1", "02:00:00:00:01:01", "10.0.12.1/30")),
                      (link, r2.add_iface("g1", "02:00:00:00:02:01", "10.0.12.2/30")),
                      (lan_b, r2.add_iface("g0", "02:00:00:00:02:00", "172.16.5.1/24")),
                      (lan_b, h3.ifaces[0]), (lan_b, h4.ifaces[0])]:
    switch.plug(iface)
r1.add_route("172.16.0.0/16", via="10.0.12.2")
r2.add_route("192.168.1.0/24", via="10.0.12.1")

def traceroute(host, dst, max_hops=6):
    global VERBOSE
    print(f"traceroute from {host.name} to {dst}")
    for ttl in range(1, max_hops + 1):
        host.log.clear()
        VERBOSE = False                       # run each probe quietly
        host.ping(dst, seq=100 + ttl, ttl=ttl)
        VERBOSE = True
        if not host.log:
            print(f"  {ttl}  * * *")
            continue
        icmp_type, source = host.log[-1]
        marks = {0: "", 11: "", 3: "  !N (network unreachable)"}
        print(f"  {ttl}  {source}{marks[icmp_type]}")
        if icmp_type in (0, 3):
            break

traceroute(h1, "172.16.5.40")
traceroute(h4, "192.168.1.20")
traceroute(h1, "172.16.9.9")
traceroute from H1 to 172.16.5.40
  1  192.168.1.1
  2  10.0.12.2
  3  172.16.5.40
traceroute from H4 to 192.168.1.20
  1  172.16.5.1
  2  10.0.12.1
  3  192.168.1.20
traceroute from H1 to 172.16.9.9
  1  192.168.1.1
  2  10.0.12.2
  3  10.0.12.2  !N (network unreachable)

The path back from H4 uses the other interface addresses of the same routers, which is what real traceroutes show too: each router answers from the interface the probe arrived on. The last trace finds that 172.16.9.9 is inside R1's 172.16.0.0/16 route, so R1 forwards it, but R2 has no route for it and reports network unreachable (shown as !N, like the real tool).

Ideas to extend it

You now have a working, byte-accurate model of a small network. Some directions to take it further:

  1. A default route: give R1 a 0.0.0.0/0 route to an "ISP" router and add a NAT translation table on R1 (see the NAT lesson) so the private hosts can reach 8.8.8.8.
  2. VLANs: add 802.1Q tags on the link between SW1 and a second switch and keep a MAC table per VLAN.
  3. UDP and ports: add a UDP header (with the pseudo-header checksum) and a tiny "DNS server" host that answers queries built with the DNS lessons' code.
  4. Link failures and dynamic routing: add a third router and a second path, run Dijkstra on the topology to fill the routing tables, then "cut" a link and recompute.
  5. A firewall: give R1 an ACL evaluated in forward() that only allows ICMP and TCP/443 from LAN A.

Test yourself

In the simulator, which addresses change as a packet travels from H1 to H3?

  1. The source and destination IP addresses
  2. The MAC addresses (per hop) and the TTL
  3. Nothing changes
  4. Only the destination IP

Why does R1 need an ARP entry for 10.0.12.2 to deliver a packet to H3?

  1. 10.0.12.2 is H3's address
  2. 10.0.12.2 is the next hop (R2), and the frame on that link must be addressed to R2's MAC
  3. ARP is needed for every IP in the packet
  4. It doesn't need one

How does the traceroute in step 4 discover each router?

  1. It asks DNS
  2. It sends pings with increasing TTL; each router where the TTL runs out answers with ICMP time exceeded
  3. It reads the routing tables directly
  4. It floods ARP requests