TExcelTAD
Home › Computer Networking › Routing & Routing Tables

Routing & Routing Tables

Routing is how a packet finds its way from one network to another. Each router (and each host) has a routing table: a list of destination networks and, for each, where to send the packet next. A router looks at the destination IP, picks the best matching route, and forwards the packet one hop closer. No single router knows the whole path; each just knows the next hop.

What's in a routing table

Column Meaning
Destination (prefix) a network such as 10.1.0.0/16, or 0.0.0.0/0 for "everything else"
Next hop (gateway) the IP of the neighbouring router to send to, or "directly connected"
Interface which port to send it out of
Metric the cost of the route, to choose between alternatives
Source how it was learned: connected, static, OSPF, BGP…

The route 0.0.0.0/0 matches every address. It is the default route, and on a host it points to the default gateway.

bash
ip route show

Sample output:

text
default via 192.168.1.1 dev wlp2s0 proto dhcp src 192.168.1.20 metric 600
10.8.0.0/24 dev tun0 proto kernel scope link src 10.8.0.6
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 linkdown
192.168.1.0/24 dev wlp2s0 proto kernel scope link src 192.168.1.20 metric 600

On Windows use route print; on macOS netstat -rn.

Longest-prefix match

Several routes can match the same address. 10.1.2.3 matches 0.0.0.0/0, 10.0.0.0/8, 10.1.0.0/16 and 10.1.2.0/24. The rule is: the most specific route (the longest prefix) wins. This lets a general route cover a big area while a specific route overrides it for one subnet.

python · try it yourself
import ipaddress

ROUTES = [
    ("0.0.0.0/0",      "203.0.113.1", "wan0"),
    ("10.0.0.0/8",     "10.255.0.1",  "eth1"),
    ("10.1.0.0/16",    "10.255.0.2",  "eth1"),
    ("10.1.2.0/24",    "connected",   "eth2"),
    ("192.168.1.0/24", "connected",   "eth0"),
    ("10.1.2.128/25",  "10.1.2.254",  "eth2"),
]
table = [(ipaddress.ip_network(p), hop, iface) for p, hop, iface in ROUTES]

def lookup(dest):
    ip = ipaddress.ip_address(dest)
    matches = [r for r in table if ip in r[0]]
    best = max(matches, key=lambda r: r[0].prefixlen)
    return best, len(matches)

for dest in ["10.1.2.3", "10.1.2.200", "10.1.99.1", "10.200.0.1", "192.168.1.7", "8.8.8.8"]:
    (net, hop, iface), n = lookup(dest)
    print(f"{dest:<12} {n} matching routes, best {str(net):<15} via {hop:<12} on {iface}")
10.1.2.3     4 matching routes, best 10.1.2.0/24     via connected    on eth2
10.1.2.200   5 matching routes, best 10.1.2.128/25   via 10.1.2.254   on eth2
10.1.99.1    3 matching routes, best 10.1.0.0/16     via 10.255.0.2   on eth1
10.200.0.1   2 matching routes, best 10.0.0.0/8      via 10.255.0.1   on eth1
192.168.1.7  2 matching routes, best 192.168.1.0/24  via connected    on eth0
8.8.8.8      1 matching routes, best 0.0.0.0/0       via 203.0.113.1  on wan0

Real routers don't scan a list: they store routes in a trie (a binary tree keyed on address bits) or in special hardware (TCAM), and find the longest match in a handful of steps even with a million routes in the table.

A routing trie

Here is a small binary trie. Each level consumes one bit of the address; the deepest node with a route that we pass on the way down is the longest match.

python · try it yourself
import ipaddress

class Node:
    def __init__(self):
        self.children = {}
        self.route = None

root = Node()

def insert(prefix, next_hop):
    net = ipaddress.ip_network(prefix)
    bits = f"{int(net.network_address):032b}"[:net.prefixlen]
    node = root
    for bit in bits:
        node = node.children.setdefault(bit, Node())
    node.route = (prefix, next_hop)

def lookup(address):
    bits = f"{int(ipaddress.ip_address(address)):032b}"
    node, best, depth = root, root.route, 0
    for bit in bits:
        node = node.children.get(bit)
        if node is None:
            break
        depth += 1
        if node.route:
            best = node.route
    return best, depth

for prefix, hop in [("0.0.0.0/0", "ISP"), ("10.0.0.0/8", "core"), ("10.1.0.0/16", "branch"),
                    ("10.1.2.0/24", "lab")]:
    insert(prefix, hop)

for dest in ["10.1.2.3", "10.1.3.3", "10.9.9.9", "172.16.0.1"]:
    (prefix, hop), depth = lookup(dest)
    print(f"{dest:<11} -> {prefix:<12} via {hop:<7} (walked {depth} bits)")
10.1.2.3    -> 10.1.2.0/24  via lab     (walked 24 bits)
10.1.3.3    -> 10.1.0.0/16  via branch  (walked 23 bits)
10.9.9.9    -> 10.0.0.0/8   via core    (walked 12 bits)
172.16.0.1  -> 0.0.0.0/0    via ISP     (walked 0 bits)

Hop by hop

Each router makes its own independent decision. Here is a packet travelling across three routers, each with its own small table. Notice that the destination IP never changes; only the next hop does:

python · try it yourself
import ipaddress

routers = {
    "R1": [("10.2.0.0/16", "R2"), ("0.0.0.0/0", "ISP")],
    "R2": [("10.2.5.0/24", "R3"), ("10.1.0.0/16", "R1"), ("0.0.0.0/0", "R1")],
    "R3": [("10.2.5.0/24", "deliver")],
}

def best_route(router, dest):
    ip = ipaddress.ip_address(dest)
    candidates = [(ipaddress.ip_network(p), hop) for p, hop in routers[router]
                  if ip in ipaddress.ip_network(p)]
    return max(candidates, key=lambda c: c[0].prefixlen)

def forward(dest, start, ttl=8):
    router = start
    while ttl > 0:
        net, hop = best_route(router, dest)
        print(f"{router}: dst {dest} matches {net} -> {hop}  (TTL {ttl})")
        if hop in ("deliver", "ISP"):
            return
        router, ttl = hop, ttl - 1
    print("TTL expired")

forward("10.2.5.77", "R1")
R1: dst 10.2.5.77 matches 10.2.0.0/16 -> R2  (TTL 8)
R2: dst 10.2.5.77 matches 10.2.5.0/24 -> R3  (TTL 7)
R3: dst 10.2.5.77 matches 10.2.5.0/24 -> deliver  (TTL 6)

How routes get into the table

Source How Typical admin distance (Cisco)
Connected automatically, for every configured interface subnet 0
Static typed in by an administrator 1
eBGP learned from another organisation 20
OSPF dynamic link-state protocol inside an organisation 110
RIP dynamic distance-vector protocol (old) 120

When two sources offer the same prefix, the router prefers the more trusted source (lower administrative distance), then the lower metric. Prefix length always comes first, though: a /24 from RIP beats a /16 from OSPF for an address inside the /24.

bash
sudo ip route add 10.50.0.0/16 via 192.168.1.254 dev eth0
ip route get 10.50.3.4

Sample output:

text
10.50.3.4 via 192.168.1.254 dev eth0 src 192.168.1.20 uid 1000
    cache

ip route get is a handy way to ask the kernel "which route would you use for this address?"

Note: Routing tables are not symmetric. The path from A to B can be different from the path from B back to A. This "asymmetric routing" is normal on the Internet, and it can confuse stateful firewalls that only see one direction.

Test yourself

A router has routes for 10.0.0.0/8, 10.20.0.0/16 and 0.0.0.0/0. Which is used for 10.20.30.40?

  1. 0.0.0.0/0
  2. 10.0.0.0/8
  3. 10.20.0.0/16
  4. All three, round robin

What does the route 0.0.0.0/0 match?

  1. Nothing
  2. Only 0.0.0.0
  3. Every IPv4 address
  4. Only private addresses

Which field of the packet changes as it is forwarded from router to router (without NAT)?

  1. Destination IP
  2. Source IP
  3. TTL
  4. Protocol