Networking Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Try for a few minutes before opening a solution.
| # | Exercise | Topics |
|---|---|---|
| 1 | Dotted decimal to binary | IPv4 addresses, bit operations |
| 2 | Subnet calculator | masks, network and broadcast addresses |
| 3 | The Internet checksum | one's complement sums, struct |
| 4 | Parse an Ethernet header | frames, MAC addresses, EtherType |
| 5 | Longest-prefix match | routing tables |
| 6 | Count switch floods | MAC learning |
| 7 | TCP sequence numbers | seq/ack arithmetic |
| 8 | Parse an HTTP response | HTTP/1.1 framing |
| 9 | Encode and decode DNS names | DNS wire format |
| 10 | Firewall rule order | first-match ACLs |
1. Dotted decimal to binary
Write to_binary(ip) that returns the address as four 8-bit groups separated by dots, without using the ipaddress module.
Expected:
192.168.1.20 -> 11000000.10101000.00000001.00010100
10.0.0.255 -> 00001010.00000000.00000000.11111111def to_binary(ip):
# TODO: split into octets and format each one as 8 binary digits
return ip
for ip in ["192.168.1.20", "10.0.0.255"]:
print(ip, "->", to_binary(ip))192.168.1.20 -> 192.168.1.20
10.0.0.255 -> 10.0.0.255
Show solution
def to_binary(ip):
return ".".join(f"{int(octet):08b}" for octet in ip.split("."))
for ip in ["192.168.1.20", "10.0.0.255"]:
print(ip, "->", to_binary(ip)):08b formats a number in binary, padded with zeros to 8 digits.
2. Subnet calculator
Write subnet_info(cidr) that returns the network address, broadcast address and number of usable hosts for an address like "172.16.77.130/26". Do the bit arithmetic yourself (you may use socket.inet_aton/inet_ntoa or your own conversion).
Expected:
172.16.77.130/26: network 172.16.77.128, broadcast 172.16.77.191, 62 hosts
10.1.200.7/20: network 10.1.192.0, broadcast 10.1.207.255, 4094 hostsdef to_int(dotted):
a, b, c, d = map(int, dotted.split("."))
return (a << 24) | (b << 16) | (c << 8) | d
def to_dotted(n):
return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0))
def subnet_info(cidr):
address, prefix = cidr.split("/")
# TODO: build the mask, then compute network, broadcast and usable hosts
return address, address, 0
for cidr in ["172.16.77.130/26", "10.1.200.7/20"]:
net, bcast, hosts = subnet_info(cidr)
print(f"{cidr}: network {net}, broadcast {bcast}, {hosts} hosts")172.16.77.130/26: network 172.16.77.130, broadcast 172.16.77.130, 0 hosts
10.1.200.7/20: network 10.1.200.7, broadcast 10.1.200.7, 0 hosts
Show solution
def subnet_info(cidr):
address, prefix = cidr.split("/")
prefix = int(prefix)
mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
network = to_int(address) & mask
broadcast = network | (~mask & 0xFFFFFFFF)
hosts = 2 ** (32 - prefix) - 2
return to_dotted(network), to_dotted(broadcast), hosts3. The Internet checksum
Implement internet_checksum(data): sum the data as 16-bit big-endian words (pad an odd length with a zero byte), fold the carries back in, and return the one's complement. Then check that a header with its checksum filled in sums to 0.
Expected:
checksum: 0x27f3
verify: 0import struct
header = bytes.fromhex("4500003c1c4640004006" + "0000" + "c0a801145db8d70e")
def internet_checksum(data):
# TODO: implement the one's complement sum
return 0
csum = internet_checksum(header)
print(f"checksum: 0x{csum:04x}")
filled = header[:10] + struct.pack("!H", csum) + header[12:]
print("verify:", internet_checksum(filled))checksum: 0x0000
verify: 0
Show solution
def internet_checksum(data):
if len(data) % 2:
data += b"\x00"
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFFThis is the IPv4 header from the IPv4 Packets lesson, so you should get the same 27f3.
4. Parse an Ethernet header
Given the first bytes of a frame, print the destination MAC, the source MAC, the EtherType name, and whether the destination is broadcast, multicast or unicast.
Expected:
dst ff:ff:ff:ff:ff:ff (broadcast) src 3c:22:fb:91:0a:7e type ARP
dst 01:00:5e:00:00:fb (multicast) src b8:27:eb:12:34:56 type IPv4
dst 00:1a:2b:3c:4d:5e (unicast) src 3c:22:fb:91:0a:7e type IPv6import struct
frames = [
bytes.fromhex("ffffffffffff3c22fb910a7e0806"),
bytes.fromhex("01005e0000fbb827eb1234560800"),
bytes.fromhex("001a2b3c4d5e3c22fb910a7e86dd"),
]
TYPES = {0x0800: "IPv4", 0x0806: "ARP", 0x86DD: "IPv6"}
for frame in frames:
# TODO: unpack the 14-byte header and classify the destination
print("dst ? src ? type ?")dst ? src ? type ?
dst ? src ? type ?
dst ? src ? type ?
Show solution
for frame in frames:
dst, src, ethertype = struct.unpack("!6s6sH", frame[:14])
if dst == b"\xff" * 6:
kind = "broadcast"
elif dst[0] & 1:
kind = "multicast"
else:
kind = "unicast"
print(f"dst {dst.hex(':')} ({kind}) src {src.hex(':')} type {TYPES[ethertype]}")Check broadcast before multicast: the broadcast address also has the group bit set.
5. Longest-prefix match
Write lookup(table, dest) that returns the next hop of the most specific matching route.
Expected:
10.1.2.3 -> R-lab
10.1.9.9 -> R-branch
10.200.0.1 -> R-core
8.8.8.8 -> ISPimport ipaddress
table = [("0.0.0.0/0", "ISP"), ("10.0.0.0/8", "R-core"),
("10.1.0.0/16", "R-branch"), ("10.1.2.0/24", "R-lab")]
def lookup(table, dest):
# TODO: find every matching prefix and return the hop of the longest one
return table[0][1]
for dest in ["10.1.2.3", "10.1.9.9", "10.200.0.1", "8.8.8.8"]:
print(dest, "->", lookup(table, dest))10.1.2.3 -> ISP
10.1.9.9 -> ISP
10.200.0.1 -> ISP
8.8.8.8 -> ISP
Show solution
def lookup(table, dest):
ip = ipaddress.ip_address(dest)
matches = [(ipaddress.ip_network(prefix), hop) for prefix, hop in table
if ip in ipaddress.ip_network(prefix)]
return max(matches, key=lambda m: m[0].prefixlen)[1]6. Count switch floods
A switch with an empty MAC table receives these frames (port, source, destination). Simulate MAC learning and count how many frames are flooded (unknown destination or broadcast) and how many are forwarded to a single port.
Expected:
flooded: 3, forwarded: 3
table: {'A': 1, 'B': 2, 'C': 3}frames = [(1, "A", "B"), (2, "B", "A"), (3, "C", "FF"), (1, "A", "C"), (3, "C", "B"), (2, "B", "D")]
table = {}
flooded = forwarded = 0
for port, src, dst in frames:
# TODO: learn the source, then flood or forward
pass
print(f"flooded: {flooded}, forwarded: {forwarded}")
print("table:", table)flooded: 0, forwarded: 0
table: {}
Show solution
for port, src, dst in frames:
table[src] = port
if dst != "FF" and dst in table:
forwarded += 1
else:
flooded += 1The floods are A→B (B unknown), C's broadcast, and B→D (D never sent anything).
7. TCP sequence numbers
A client's initial sequence number is 7000. After the handshake it sends three segments of 500, 1200 and 300 bytes, then closes with FIN. Print the sequence number of each segment and the ACK the server sends for it. Remember that SYN and FIN each consume one sequence number.
Expected:
data seq=7001 len=500 -> ACK 7501
data seq=7501 len=1200 -> ACK 8701
data seq=8701 len=300 -> ACK 9001
FIN seq=9001 -> ACK 9002isn = 7000
sizes = [500, 1200, 300]
seq = isn # TODO: the SYN used up one number
for size in sizes:
print(f"data seq={seq} len={size} -> ACK {seq}") # TODO: correct ACK and advance seq
print(f"FIN seq={seq} -> ACK {seq}") # TODOdata seq=7000 len=500 -> ACK 7000
data seq=7000 len=1200 -> ACK 7000
data seq=7000 len=300 -> ACK 7000
FIN seq=7000 -> ACK 7000
Show solution
seq = isn + 1
for size in sizes:
print(f"data seq={seq} len={size} -> ACK {seq + size}")
seq += size
print(f"FIN seq={seq} -> ACK {seq + 1}")8. Parse an HTTP response
Split the raw response into status code, headers (as a dict with lowercase names) and body. Use Content-Length to cut the body: anything after it belongs to the next response on the connection.
Expected:
status: 404
content-type: text/plain
body: b'no such page'
leftover: b'HTTP/1.1 200 OK'raw = (b"HTTP/1.1 404 Not Found\r\n"
b"Content-Type: text/plain\r\n"
b"Content-Length: 12\r\n"
b"\r\n"
b"no such pageHTTP/1.1 200 OK")
def parse_response(data):
# TODO: split head and body, parse the status line and headers
return 0, {}, b"", data
status, headers, body, leftover = parse_response(raw)
print("status:", status)
print("content-type:", headers.get("content-type"))
print("body:", body)
print("leftover:", leftover)status: 0
content-type: None
body: b''
leftover: b'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nno such pageHTTP/1.1 200 OK'
Show solution
def parse_response(data):
head, _, rest = data.partition(b"\r\n\r\n")
lines = head.decode("ascii").split("\r\n")
status = int(lines[0].split(" ")[1])
headers = {}
for line in lines[1:]:
name, _, value = line.partition(":")
headers[name.strip().lower()] = value.strip()
length = int(headers.get("content-length", 0))
return status, headers, rest[:length], rest[length:]9. Encode and decode DNS names
Write encode(name) (length-prefixed labels ending in a zero byte) and decode(data) (the reverse, without compression pointers).
Expected:
03 77 77 77 07 65 78 61 6d 70 6c 65 03 63 6f 6d 00
www.example.com
04 6d 61 69 6c 02 63 73 03 75 6e 69 02 76 6e 00
mail.cs.uni.vndef encode(name):
# TODO: length-prefixed labels, then a zero byte
return name.encode()
def decode(data):
# TODO: read labels until the zero byte
return data.decode()
for name in ["www.example.com", "mail.cs.uni.vn"]:
wire = encode(name)
print(wire.hex(" "))
print(decode(wire))77 77 77 2e 65 78 61 6d 70 6c 65 2e 63 6f 6d
www.example.com
6d 61 69 6c 2e 63 73 2e 75 6e 69 2e 76 6e
mail.cs.uni.vn
Show solution
def encode(name):
out = b""
for label in name.split("."):
out += bytes([len(label)]) + label.encode("ascii")
return out + b"\x00"
def decode(data):
labels, i = [], 0
while data[i] != 0:
length = data[i]
labels.append(data[i + 1:i + 1 + length].decode("ascii"))
i += 1 + length
return ".".join(labels)10. Firewall rule order
The rules below are in the wrong order: the office can't reach SSH. Reorder them (don't change any rule) so that the office network may use SSH, everyone may use HTTPS, and everything else is denied.
Expected:
198.51.100.9 tcp/22: allow
192.0.2.5 tcp/22: deny
192.0.2.5 tcp/443: allow
192.0.2.5 tcp/3306: denyimport ipaddress
rules = [
("deny", "0.0.0.0/0", None), # deny everything
("deny", "0.0.0.0/0", 22),
("allow", "0.0.0.0/0", 443),
("allow", "198.51.100.0/24", 22),
]
# TODO: put the rules in the right order
def decide(src, port):
for action, net, p in rules:
if ipaddress.ip_address(src) in ipaddress.ip_network(net) and p in (None, port):
return action
return "deny"
for src, port in [("198.51.100.9", 22), ("192.0.2.5", 22), ("192.0.2.5", 443), ("192.0.2.5", 3306)]:
print(f"{src} tcp/{port}: {decide(src, port)}")198.51.100.9 tcp/22: deny
192.0.2.5 tcp/22: deny
192.0.2.5 tcp/443: deny
192.0.2.5 tcp/3306: deny
Show solution
rules = [
("allow", "198.51.100.0/24", 22),
("deny", "0.0.0.0/0", 22),
("allow", "0.0.0.0/0", 443),
("deny", "0.0.0.0/0", None),
]Specific rules first, the catch-all deny last. (The deny 0.0.0.0/0 port 22 rule is now redundant, because the final rule denies it anyway, but keeping it makes the intent explicit.)
Test yourself
In exercise 2, why is the number of usable hosts 2^(32 − prefix) − 2?
- Two addresses are reserved for routers
- The network address and the broadcast address can't be assigned to hosts
- Two bits are used for the checksum
- It's a convention with no reason
In exercise 4, why must the broadcast check come before the multicast check?
- Broadcast frames are larger
- ff:ff:ff:ff:ff:ff also has the group (I/G) bit set, so it would be classified as multicast
- Multicast frames have no source MAC
- The order doesn't matter
In exercise 7, why does the ACK for the FIN equal the FIN's sequence number + 1?
- FIN carries one byte of data
- FIN consumes one sequence number, like SYN
- ACKs are always odd
- The server adds a random offset