In this lesson, you will learn how the Linux kernel selects the best path for a packet when multiple routes to the same destination exist, specifically by manipulating metrics and administrative distances.
The Route Selection Hierarchy
When the kernel's Kernel Routing Table needs to forward a packet, it doesn't just look for a match; it often finds multiple overlapping entries. To resolve these, the kernel employs a hierarchical selection algorithm based on two primary factors: Destination Prefix Length (Longest Prefix Match) and Route Metric.
While "Longest Prefix Match" is an immutable rule of networking, the Route Metric allows you to influence the decision-making process manually. When two routes have the same prefix length, the kernel defaults to the one with the lowest numeric metric value.
Tuning Metrics for Traffic Steering
Think of the metric as a "cost" associated with a path. A lower metric implies a more desirable, lower-cost route. You can use this to steer traffic across specific links—for example, preferring a high-speed fiber uplink (metric 100) over a secondary cellular backup (metric 500).
You can modify these during route creation using ip route. For instance, to ensure a specific gateway is preferred for your local network, you can assign it a lower metric:
# Add a primary route with a low metric
ip route add 192.168.1.0/24 dev eth0 metric 100
# Add a backup route with a higher metric
ip route add 192.168.1.0/24 dev wlan0 metric 500
Administrative Distances and Protocol Weighting
In environments where you run dynamic routing protocols (via daemons like FRR or BIRD), the kernel differentiates routes by their source. An "Administrative Distance" acts as a trust factor. If the kernel learns the same route from both an OSPF daemon and a static configuration, it prefers the one with the lower administrative distance. By tuning these values, you control the "source hierarchy," ensuring that manually defined (static) routes generally supersede dynamically learned ones, or vice versa, depending on your network policy.
By strategically assigning metrics and understanding the kernel’s selection hierarchy, you gain fine-grained control over traffic engineering, ensuring high-priority packets traverse the most efficient path available.
Key Takeaway: The Linux kernel selects routes by first finding the longest matching prefix and then choosing the path with the lowest metric to break ties between equal-length entries.