Networking Tutorial · Routing and Network Services · Lesson 16 of 28
Routing and Gateways
How routers and route tables decide where packets go: longest-prefix match, default routes and gateways.
Route tables
Every host and router has a route table: a list of destination ranges and where to send matching packets.
$ ip route # Linux
default via 192.168.1.1 dev wlan0
192.168.1.0/24 dev wlan0 proto kernel scope link
10.8.0.0/16 via 10.8.0.1 dev tun0 # VPN
- Destinations on the local subnet are delivered directly.
- Everything else goes to a gateway, a router that forwards it further.
- The default route (
0.0.0.0/0, or::/0for IPv6) matches everything: "if nothing more specific matches, send it here".
Longest-prefix match
When several routes match, the most specific one (the longest prefix) wins. 10.1.2.0/24 beats
10.0.0.0/8, which beats 0.0.0.0/0.
import ipaddress
ROUTES = [
("10.0.0.0/16", "local"),
("10.1.0.0/16", "vpc-peering to shared-services"),
("10.1.2.0/24", "vpn to office"),
("0.0.0.0/0", "nat-gateway"),
]
def route(destination):
ip = ipaddress.ip_address(destination)
matches = [(ipaddress.ip_network(net), target) for net, target in ROUTES if ip in ipaddress.ip_network(net)]
net, target = max(matches, key=lambda m: m[0].prefixlen)
return f"{destination:12} -> {target:31} (via {net})"
for dest in ["10.0.4.20", "10.1.9.9", "10.1.2.7", "52.94.1.10"]:
print(route(dest))
Output
10.0.4.20 -> local (via 10.0.0.0/16) 10.1.9.9 -> vpc-peering to shared-services (via 10.1.0.0/16) 10.1.2.7 -> vpn to office (via 10.1.2.0/24) 52.94.1.10 -> nat-gateway (via 0.0.0.0/0)
Routing in the cloud
A cloud subnet is associated with a route table. The difference between a "public" and a "private" subnet is just its default route: to an internet gateway, or to a NAT gateway. You'll build exactly this in the Cloud Networking section.
Between networks and providers, routers exchange routes automatically with BGP, the protocol that holds the internet together. You'll meet it with VPNs and dedicated connections (AWS Direct Connect, Azure ExpressRoute, Google Cloud Interconnect).
Test yourself
A route table has 10.0.0.0/8 -> A, 10.20.0.0/16 -> B and 0.0.0.0/0 -> C. Where does 10.20.5.1 go?
ABCIt is dropped
Show answer
Answer: B
All three match, and the longest prefix (/16) wins.