Forwarding with longest-prefix match
A router forwards each packet by looking up its destination IP address in a forwarding table. Each entry is a prefix plus a next hop. Several entries can match the same address, for example a broad default route and a narrow route to one lab network. The rule is longest-prefix match: the router uses the matching entry with the longest prefix, because a longer prefix is more specific.
Python
import ipaddress
routes = [
(ipaddress.ip_network("0.0.0.0/0"), "default gateway"),
(ipaddress.ip_network("10.0.0.0/8"), "corporate core"),
(ipaddress.ip_network("10.1.0.0/16"), "branch office"),
(ipaddress.ip_network("10.1.2.0/24"), "lab switch"),
]
def next_hop(destination):
address = ipaddress.ip_address(destination)
matches = [(network.prefixlen, hop) for network, hop in routes if address in network]
return max(matches)[1]
for destination in ("10.1.2.9", "10.1.9.9", "10.200.0.1", "8.8.8.8"):
print(destination, next_hop(destination))