How does a router choose between overlapping routes? (Longest prefix match)
My routing table has 10.0.0.0/8, 10.1.0.0/16, and 0.0.0.0/0. A packet for 10.1.2.3 matches all three. Which wins and why?
1 Answer
The most specific route wins: longest prefix match. 10.1.2.3 matches /8, /16, and /0 — the router picks 10.1.0.0/16 because 16 matching bits beats 8 beats 0. Only when prefix lengths tie does it compare administrative distance (which source to believe: connected 0, static 1, eBGP 20, OSPF 110…), and only when AD also ties does the protocol's metric break the tie (possibly load-balancing equal metrics). Order matters: specificity → AD → metric — a static /24 beats an OSPF /24, but an OSPF /24 beats a static /16 for a host inside both, because prefix length is evaluated first. The default route (0.0.0.0/0) is simply the least specific match possible: the packet's last resort, not a competitor to real routes.