28/35
Part 7 of 7 · Follow-upsLearn and do

A router forwards by the longest matching prefix, and a trie over 32 bits finds it in one walk

A router sends a packet by the most specific route that covers its address. RFC 4632 puts it in one line: "Forwarding in the Internet is done on a longest-match basis." Sedgewick and Wayne's example is an address, 128.112.136.12, that goes to the route for 128.112 because that's the longest matching prefix the table knows.

A route like 128.112.0.0/16 covers every address whose first 16 bits match. So a trie over bits, two children per node, answers it in one walk. Insert each route's first bits. Then walk an address's 32 bits, and remember the last route you passed:

import ipaddress


def add_route(trie, cidr, hop):
    net = ipaddress.ip_network(cidr)
    bits = format(int(net.network_address), "032b")[: net.prefixlen]
    node = trie
    for bit in bits:
        node = node.setdefault(bit, {})
    node[END] = hop


routes = {}
add_route(routes, "0.0.0.0/0", "default")
add_route(routes, "128.112.0.0/16", "campus")
add_route(routes, "128.112.136.0/24", "lab")
print([next_hop(routes, a) for a in ["128.112.136.12", "128.112.9.9", "8.8.8.8"]])
Predict

Routes: 0.0.0.0/0 goes to default, 128.112.0.0/16 to campus and 128.112.136.0/24 to lab. Where does 128.112.9.9 go?

Pick one to see what it prints.
Pick an answer above to see the rest