A table usually has a route for every address at once, and still the kernel picks the most specific one.
The default route matches any address: it is the /0 prefix, written as default in the table. Through it the machine reaches every network that has no line of its own.
When several lines match an address, the kernel takes the one with the longer prefix: /32 is more specific than /24, and /24 more than /0. So default only applies when no other line matches.
The metric is the metric N number at the end of a line. It decides between routes with the same prefix: the lower number wins. A longer prefix wins whatever the metric. The order of lines in the output of ip route does not affect the choice.
| Line | For 203.0.113.5 |
|---|---|
default via 192.0.2.254 metric 100 |
matches, prefix /0 |
203.0.113.0/24 via 192.0.2.1 |
matches, prefix /24 — chosen |
This is the client's table. Through which gateway will a packet for 198.51.100.20 leave?
default via 192.0.2.254 dev lab0 metric 10
198.51.100.20 via 192.0.2.1 dev lab0 metric 500
-
The order of lines in the output does not affect the choice.
ip route get 198.51.100.20shows the kernel's decision. -
The metric only decides between lines with the same prefix. Here it is
/32against/0, and the longer prefix wins. -
The kernel picks one line: the matching one with the longest prefix.
ip route get 198.51.100.20prints the same gateway every time.
Both lines match the address, but /32 is longer than /0, so the line via 192.0.2.1 is chosen. The metric is compared only when the prefixes are equal.
Key points
-
defaultis the/0prefix and matches any address. - Of the matching lines, the kernel picks the longest prefix.
- The metric only decides between routes with the same prefix.