Whenever somebody asks "which route will this packet take?", the answer starts with one rule: the most specific matching route wins, regardless of the order the routes were added.
Take this table on a Linux box:
$ ip route
default via 192.0.2.1 dev eth0
198.51.100.0/24 dev eth1
198.51.100.128/25 via 198.51.100.2 dev eth1
Now ask the kernel what it will do:
$ ip route get 198.51.100.200
198.51.100.200 via 198.51.100.2 dev eth1
$ ip route get 198.51.100.50
198.51.100.50 dev eth1
$ ip route get 203.0.113.9
203.0.113.9 via 192.0.2.1 dev eth0
198.51.100.200matches the/24, the/25and the default. The/25is the longest prefix (25 bits), so it wins: the next hop is198.51.100.2.198.51.100.50matches the/24and the default, but not the/25(it covers .128 to .255). The/24wins: delivered directly.203.0.113.9matches only the default route, which is/0, the shortest possible prefix. That is why it is the route of last resort.
Two consequences worth remembering:
- A more specific route overrides a broader one without deleting it. That is how you carve an exception out of a big block, and also how a mistaken
/32can send one host's traffic to the wrong place for weeks while everything else works. - Routers do this lookup for every packet, so the hardware uses special memory (TCAM) or tries, built for exactly this rule.
Specific beats general. Every packet agrees on this. The default waits last.