Card 02/ 10
Longest Prefix Match: The Most Specific Route Wins
When several routes match one address, the router takes the one with the longest prefix.
Longest prefix match is the rule a router uses when more than one row of its routing table matches a destination: it chooses the row with the longest prefix, because that row describes the smallest, most specific range containing the address. The order of rows in the table does not matter.
Picture a company whose routers know three routes: the default route to the internet, 10.0.0.0/8 for every internal network, and 10.1.0.0/16 for one data centre reached over a dedicated line. A packet for 10.1.2.3 matches all three. The company wants it on the dedicated line, and longest prefix match is what sends it there without anyone listing exceptions.
When No row's range contains the destination, not even a default route
, chooseDrop the packet and send back an ICMP "destination unreachable" message.
When Exactly one row's range contains the destination
, chooseUse that row.
When Several rows' ranges contain the destination
, chooseUse the row with the longest prefix, the most specific range.
A row matches when the destination, with its host bits set to zero under that row's prefix, equals the row's network address. Every match is a range that contains the address; the longest prefix is the narrowest of those ranges.
The default route shows the rule at its extremes. Its prefix is /0, so it matches every address, and it is also the shortest possible prefix, so it loses to any other match. It is used only when nothing else fits, which is exactly what a default should do.
The rule lets networks be described in layers. A broad route covers a whole region, and a narrow route overrides it for one part without the broad route having to list exceptions. Engineers use this on purpose: adding a /24 route to steer one subnet somewhere else, while the /16 around it continues as before.
It also explains a common surprise. Adding a specific route can capture traffic nobody meant to move, because the new route wins for every address inside it, regardless of when it was added or where it sits in the list.
So when you predict where a packet goes, list every row that contains its destination, then take the longest prefix; never read the table top to bottom and stop at the first match.
← → move through sections and cards