Sub topic 13
Longest-prefix match in routing
This chapter assumes you can compute a network address and broadcast address from a prefix length (for example, 10.1.4.128/25 covers 10.1.4.128 to 10.1.4.255). It also assumes you know what a routing table is: a list of destination prefixes, each paired with a next hop or exit interface. Here you will see how a router chooses among several entries that all contain the same destination address.
Why more than one route can match
Summarization and subnetting produce overlapping prefixes on purpose. A router can hold 10.0.0.0/8 for "everything in the corporate network", 10.1.0.0/16 for one site, and 10.1.4.0/24 for one lab. The address 10.1.4.200 falls inside all three. The router needs a rule that picks exactly one.
The rule is longest-prefix match: of all routes whose prefix contains the destination address, use the one with the longest prefix length. A longer prefix fixes more leading bits, so it describes a smaller and more specific block of addresses. The router prefers the most specific information it has.
The matching procedure
For each packet, the router takes the destination address and does the following:
- Test every route: does the destination, ANDed with the route's mask, equal the route's network address?
- Collect the routes that pass the test. These are the candidates.
- Pick the candidate with the largest prefix length.
- Forward the packet to that route's next hop.
The test in step 1 is the same bitwise AND used in the subnet mask chapter. A route matches when the first n bits of the destination equal the first n bits of the route's network address, where n is the prefix length.
A worked example in binary
Consider the destination 10.1.4.200 and two candidate routes, 10.1.4.0/24 and 10.1.4.128/25. The last octet of the destination is 200, which is 11001000 in binary.
| Route | Prefix length | Bits that must match | Last-octet bits compared | Result |
|---|---|---|---|---|
| 10.1.4.0/24 | 24 | First 24 bits | None (the whole last octet is host bits) | Match |
| 10.1.4.128/25 | 25 | First 25 bits | First bit of 11001000 is 1, and 128 is 10000000, so the first bit is 1 | Match |
| 10.1.4.64/26 | 26 | First 26 bits | First two bits are 11, but 64 is 01000000, which starts with 01 | No match |
Both the /24 and the /25 match. The /25 is longer, so it wins. The /26 never competes, because 10.1.4.200 is outside 10.1.4.64 to 10.1.4.127.
Implementing the lookup in Python
The code below builds the same table as the diagram and performs the lookup with the ipaddress module. The order of the routes in the list does not matter, because the lookup selects by prefix length and not by position.
import ipaddress
routes = [
("0.0.0.0/0", "isp"),
("10.0.0.0/8", "core"),
("10.1.0.0/16", "site-b"),
("10.1.4.0/24", "lab"),
("10.1.4.128/25", "dmz"),
]
table = [(ipaddress.ip_network(prefix), hop) for prefix, hop in routes]
def lookup(address):
ip = ipaddress.ip_address(address)
candidates = [(net, hop) for net, hop in table if ip in net]
if not candidates:
return None
return max(candidates, key=lambda route: route[0].prefixlen)
for addr in ["10.1.4.200", "10.1.4.20", "10.1.9.9", "10.200.1.1", "8.8.8.8"]:
net, hop = lookup(addr)
print(addr, "->", net, "via", hop)
# 10.1.4.200 -> 10.1.4.128/25 via dmz
# 10.1.4.20 -> 10.1.4.0/24 via lab
# 10.1.9.9 -> 10.1.0.0/16 via site-b
# 10.200.1.1 -> 10.0.0.0/8 via core
# 8.8.8.8 -> 0.0.0.0/0 via ispThis linear scan is easy to read, but it is not how routers work. A router with hundreds of thousands of routes cannot test each one per packet. Real forwarding hardware uses a binary trie or ternary content-addressable memory (TCAM). A trie walks the destination address one bit at a time and remembers the last route it passed, so the cost depends on the address length (32 bits) and not on the number of routes. TCAM compares the address against every stored prefix in parallel and returns the longest match in hardware.
Special cases
The default route
0.0.0.0/0 has a prefix length of zero, so it constrains no bits and matches every address. Because its length is the shortest possible, it is chosen only when nothing more specific matches. This is why a host or edge router can send "everything else" to its ISP with a single entry.
Host routes
A /32 route matches exactly one address. It always beats any shorter prefix that contains that address. Operators use /32 routes for loopback interfaces, for steering traffic to one server, and for blackholing a single attacked address.
Discard routes for summaries
When a router advertises a summary such as 10.1.0.0/16 but owns only some of the subnets inside it, traffic to the unused part would match the summary and could loop back toward the router that advertised it. A common fix is a static route for the summary pointing to a discard (null) interface. Real subnets inside the /16 are still more specific and win. Packets for unallocated space match only the discard route and are dropped there.
What happens when prefix lengths tie
Two routes with the same prefix and length cannot both be installed as the best path by default, because both would match every address equally. Routers resolve this with a fixed order of tie-breakers:
- Longest prefix wins, regardless of how the route was learned.
- If the same prefix is offered by several sources (static, OSPF, BGP), the lowest administrative distance wins. This is a vendor-defined trust ranking.
- Within one protocol, the lowest metric wins.
- If routes are still equal, many routers install both and load-balance (equal-cost multipath).
Longest-prefix match is applied first. A /24 learned from a low-trust source still beats a /16 learned from a high-trust source, because administrative distance and metric are compared only among routes for the same prefix.
Common errors and gotchas
- Choosing by metric or order instead of length. Learners often assume the first or cheapest matching route is used. Length is compared before cost.
- Forgetting that routes can disappear. If 10.1.4.0/24 is withdrawn because its link fails, destinations in it fall back to the next-longest match, here 10.1.0.0/16. Packets are then sent toward a router that may not know where the lab is. Summaries can hide failures for this reason.
- Overlaps that are not nested. CIDR blocks either nest completely or do not overlap at all. Two valid prefixes cannot partially overlap. If you find a partial overlap, one of the prefixes is mis-aligned.
- Assuming the default route is checked first or last in the table. Its position is irrelevant. It is the least specific route, so it loses to every other match.
- Unintended hijacks. Because the more specific prefix wins on the whole internet, anyone who announces a /24 inside your /16 attracts that traffic. Filtering on prefix length and origin is the defense. This is also why a /24 is commonly the longest prefix accepted in global BGP.
Connecting back to summarization
Summarization and longest-prefix match depend on each other. A router can advertise one summary for four /24 networks because neighbors will use longest-prefix match to find the specific route when they hold one, and the summary when they do not. A summary is only safe when every address it covers is either reachable through the advertiser or deliberately discarded.
Exercise
A router holds these routes: 192.168.0.0/16 via R1, 192.168.64.0/18 via R2, 192.168.64.0/20 via R3, and 0.0.0.0/0 via R4. Which next hop is used for a packet to 192.168.70.5, and which for a packet to 192.168.90.5?
Show answer
For 192.168.70.5, the /16 matches. The /18 covers 192.168.64.0 to 192.168.127.255, so it matches. The /20 covers 192.168.64.0 to 192.168.79.255, and 70.5 falls inside, so it matches too. The default route also matches. The longest is the /20, so the packet goes to R3. For 192.168.90.5, the /20 does not match, because 90 is above 79. The /18 does match (90 is within 64 to 127), so the packet goes to R2.
Exercise
Four /24 networks 10.8.0.0/24 through 10.8.3.0/24 are summarized as 10.8.0.0/22 and advertised to a neighbor. The 10.8.2.0/24 network goes down. Where does the neighbor send a packet to 10.8.2.9, and what could you add on the advertising router to avoid a loop?
Show answer
The neighbor still holds only the /22 summary, so it keeps sending the packet to the advertising router, because the summary still matches and the failure is hidden. The advertising router no longer has a specific route for 10.8.2.0/24. Without a covering route it may send the packet back out its default route toward the neighbor, which creates a loop. Adding a static route for 10.8.0.0/22 pointing to a discard interface fixes this. The three live /24 routes remain more specific, and a packet to the dead network matches only the discard route and is dropped.