On linux, by default, even when you have multiple network interfaces, you can only have 1 default gateway. This wasn’t working out for me because I had traffic coming in from network 2 routed back to the originator through network 1 and dropped because return packets were coming from an unknown source. Using the old route tool, you are only able to specify a specific gateway for a specific network, but this wouldn’t work out because traffic from both network 2 and 1 came from the internet. We couldn’t segment on that. So what to do?

iproute2 to the rescue!

You can set up rules that traffic from a specific IP address on a specific interface is routed through a separate gateway than the default gateway. Here’s the code I used:


echo "1 rt2" >> /etc/iproute2/rt_tables
ip route add 192.168.2.0/24 dev tun0 src 192.168.2.2 table rt2
ip route add default via 192.168.2.1 dev tun0 table rt2
ip rule add from 192.168.2.2/32 table rt2
ip rule add to 192.168.2.2/32 table rt2

192.168.2.0 is network 2.
192.168.2.2 is the 2nd IP address on network 2.
192.168.2.1 is network 2 gateway.

This should work without disrupting regular traffic on the default gateway. Only traffic received from the secondary NIC/IP will be routed to the secondary gateway.

More reading…

Leave a Reply