hop 16 of 32 · 5 min
How a router decides
A router receives a packet, looks at the destination IP, and picks an outgoing interface. It does this millions of times a second, and it does it without knowing the whole path.
Longest prefix match
A routing table is a list of prefixes, and the most specific match wins:
| Destination | Next hop |
|---|---|
| 0.0.0.0/0 | 10.0.0.1 |
| 172.16.0.0/16 | 10.0.0.2 |
| 172.16.5.0/24 | 10.0.0.3 |
A packet for 172.16.5.42 matches all three. The /24 is the most specific, so it goes to 10.0.0.3. A packet for 172.16.9.1 matches the first two, and takes the /16. Anything else takes the default route.
Where the table comes from
Distance vector, such as RIP. Each router tells its neighbours the whole table it has. Simple, and it converges slowly: a failure ripples outward one hop at a time, and can loop while it does. RIP caps hop count at 15 partly to limit the damage.
Link state, such as OSPF. Each router tells everyone about its own direct links only. Every router builds the same map and runs Dijkstra on it. Converges fast, costs more memory and processing.
Path vector, BGP. Used between organisations, carries the whole path, and chooses on policy rather than distance: who you have an agreement with matters more than how many hops it is.