IP Routing & Policy Routing
ip route, routing tables, default gateway, policy routing with ip rule, and ECMP load balancing.
Overview
Overview Linux kernel routing determines where outgoing packets are sent. Every packet consults the routing table, and the kernel applies longest prefix match to select the best route.
The routing table: ip route show (the modern replacement for the obsolete route command) displays the main routing table. Output fields: destination network, via (gateway IP), dev (outgoing interface), src (preferred source IP), metric (preference — lower is preferred). The default route (0.0.0.0/0) matches all destinations not covered by more specific routes.
Longest prefix match: When multiple routes match a destination, the most specific (longest prefix) wins. A /32 host route beats a /24 subnet route which beats the default /0 route.
Adding and removing routes:
Policy routing (ip rule): Linux supports multiple routing tables (0-252) plus main (253), default (254), and local (255). ip rule list shows policy rules ordered by priority. When a rule matches (by source IP, mark, interface, etc.), the kernel consults that rule's table. This enables source-based routing — essential for multi-homed servers where reply traffic must exit the same interface it arrived on.
ECMP (Equal-Cost Multi-Path): Multiple gateways with equal cost: ip route add default nexthop via 10.0.0.1 weight 1 nexthop via 10.0.0.2 weight 1. Kernel hashes the packet's 5-tuple to select the path.
ip route get IP: Test which route and source IP would be used for a specific destination — invaluable for debugging routing issues.
Key concepts
- Longest prefix match
- ip route show/add/del
- Policy routing with ip rule
- ECMP
Interview questions
- A server has two network interfaces. HTTP requests come in on eth0 but replies go out eth1. How do you fix this with policy routing?
- How does the Linux kernel select a route when multiple routes match? Walk through the algorithm.
Sign up free to read the full topic
More Linux topics
Start free on Cariara · Coding problems · System design studio