IP & routingIntermediate

Longest-prefix match

“A router has routes for `10.0.0.0/8`, `10.4.0.0/16` and `0.0.0.0/0`. A packet arrives for `10.4.7.9`. Which route wins, and why is that the rule?”

What this tests

  • The lookup rule and its rationale (specificity)
  • How the default route fits
  • What the data structure and the failure modes look like

Answers by level

Read the beginner answer first and notice what is missing.

All three routes match 10.4.7.9 — the default matches everything, /8 matches anything starting with 10, /16 matches 10.4.x.x — and the router picks the one with the longest prefix, 10.4.0.0/16. The rule encodes specificity: a longer prefix is a more precise statement about where that address lives. It is what lets a table hold a broad route ("everything in 10/8 goes to the core") and carve exceptions out of it ("except 10.4/16, which goes to the Frankfurt link") without listing every subnet. The default route is simply the shortest possible prefix, so it loses to anything.

Host routes (/32 in IPv4, /128 in IPv6) are the other extreme: they always win, which is how VPN clients steer one server through the tunnel, and how a stray /32 can hijack traffic to a single address. Between matches of equal length, metric/administrative distance decides; equal-cost routes can be used together (ECMP), hashing flows across paths.

The same lookup runs on every host, not just routers: your laptop chooses between 192.168.1.0/24 dev wlan0 (on-link), a VPN’s 10.0.0.0/8 dev tun0, and default via 192.168.1.1. When a VPN pushes a /16 that overlaps the office network, longest-prefix match sends office traffic into the tunnel — silently. ip route get <dst> on Linux shows the winner.

Green flags · Red flags

Strong green flag · Explains longest-prefix match as a trie walk and connects it to the DSA trie topic unprompted.
Green flags
  • Picks the /16 and explains specificity as the reason
  • Places the default route as the shortest prefix, not a special case
  • Mentions host routes, VPN overlap or metric tie-breaks
  • Knows the lookup runs on hosts too and names ip route get or equivalent
  • Relates prefix length to BGP hijacks or table size
Red flags
  • Picks the first route listed or the one with the lowest metric regardless of prefix
  • Thinks the default route has priority as a fallback "checked first"
  • Cannot explain why more specific should win
  • Unaware that overlapping routes are a common outage source

Follow-up questions

F1
What happens if a /32 route to your DNS server points at a down interface?
F2
Why do ISPs reject BGP announcements longer than /24?
F3
What data structure would you use to implement the lookup?

Scenario

After connecting to the corporate VPN, engineers lose access to the office printer at 10.4.7.9, while everything else works. Show the routing-table entries that explain this and how to fix it without disconnecting the VPN.

Learn this topic