Linux using wrong default gateway
I have two internet connections connected over two different network interfaces (ethernet and wifi). The ip addresses configured are 192.168.1.10 and 192.168.2.5 respectively. When I use
ip route get 8.8.8.8
the system uses the default gateway with the lowest metric (the ethernet route). But when I do ip route get from 192.168.2.5 8.8.8.8
the system still tries to use the ethernet gateway rather than the wifi gateway:
8.8.8.8 from 192.168.2.5 via 192.168.1.1 dev eno1 uid 1000
Why is this happening?
My routing table:
default via 192.168.1.1 dev eno1 proto dhcp src 192.168.1.10 metric 100
default via 192.168.2.1 dev wlan0 proto dhcp src 192.168.2.5 metric 600
<subnet routes>
You can, by definition, have only one working default route. This is the route taken by default (hence its name) for all traffic that doesn’t have a specific entry in your routing table.
A route is defined in terms of its destination. You can specify any of the host’s IP addresses as the source of the traffic but they will all use the same routing table to decide how to get to the destination.
Actually this isn’t strictly true as you can have different namespaces and routing tables, but that’s a complexity outside this answer
I think what you’re trying to do is set up "source based routing". Typically routing is destination based.
To do this we need to make use of advanced ip
functionality, by creating a second route table and telling the system when to use that table.
So first add a line to the end of /etc/iproute2/rt_tables
that reads something like
100 wifiroute
Now you can use this table with the command
ip rule add from 192.168.2.5 table wifiroute
And finally add a default route to that table
ip route add default via 192.168.2.1 dev wlan0 table wifiroute
Of course these two ip
commands will be lost on reboot so you should ensure they are made part of the boot sequence.
You should now be able to test this, e.g. with traceroute
traceroute www.google.com
traceroute www.google.com -s 192.168.2.5
The second one should go out via wlan0 because we’re setting the source address.
You can see the routing table with ip route show table wifiroute
; you can see all routes from all tables with ip route show table all