Routes and ip route get
Every packet the host sends goes through a route lookup. The kernel picks the most specific (longest prefix) route that contains the destination. If several are equally specific, it picks the lowest metric.
A typical host has just two routes:
- a connected route for its own subnet, added automatically when you assign an address (
proto kernel scope link), which means "deliver directly on this LAN", and - a default route (
0.0.0.0/0), meaning "for anything else, send it to this gateway".
Don't try to work out the answer from ip route by eye: ask the kernel. ip route get <destination> shows exactly which route, interface, gateway and source address would be used. It's the single most useful routing command on Linux.
A router is just a host with more connected routes and net.ipv4.ip_forward=1.
root@client:~# ip route
default via 192.0.2.1 dev eth0
192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.10
root@client:~# ip route get 198.51.100.20
198.51.100.20 via 192.0.2.1 dev eth0 src 192.0.2.10 uid 0
cache
root@client:~# ip route get 192.0.2.50
192.0.2.50 dev eth0 src 192.0.2.10 uid 0
cache
root@router:~# ip route
192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.1
198.51.100.0/24 dev eth1 proto kernel scope link src 198.51.100.1 - Line 2: The default route: anything without a more specific match goes to 192.0.2.1.
- Line 3: The connected route, created automatically from the address.
scope linkmeans destinations are reached directly, without a gateway. - Lines 4–6: The kernel's actual decision for the server: via the gateway, out of eth0, with source address 192.0.2.10.
- Lines 7–9: A neighbour on the same subnet: no
via. The client will ARP for 192.0.2.50 itself. - Lines 10–12: The router has only connected routes, one per interface. That's enough because both subnets touch it directly.
Interactive: Route lookup The client's routing table. Pick a destination or type one, then edit the table: delete the default route, or add 10.0.0.0/8 and 10.20.0.0/16 and look up 10.20.1.1. (needs JavaScript)
Check your understanding
A laptop has two default routes: via Ethernet with metric 100, and via Wi-Fi with metric 600. Which is used?
- Both, alternating packets
- Ethernet, because the lower metric wins among equally specific routes
- Wi-Fi, because it was added last
- Neither; duplicate default routes are an error