Linux: Routes for using additional gateways
When having multiple network interfaces assigned to a machine, one must take care of his default gateway, otherwise things are getting weird.
Rule 1: Only one default gateway for access to foreign networks
When a host is addressed, whose IP is outside of the current subnet and no additional routing rules are defined, the default gateway is asked to route the data to that IP. When that gateway cannot reach the according host, the transmission fails.
Rule 2: Add custom subnet gateways as networking route
For every known subnet that should be contacted over a specific gateway, we must add a networking route. The command is called route and is used like that:
route add [-net|-host] <IP/Net> netmask <Mask> gw <Gateway IP> dev <Int>X
A concrete example that adds a static route:
route add -net 192.0.0.0 netmask 255.255.255.0 gw 192.0.1.1 dev eth0
In this example we add an entry to the kernel ip tables that routes all packets to IPs from 192.0.0.[1-255] through the gateway 192.0.1.1. Eg. when I do ping 192.0.0.15, the target IP is part of the subnet we defined in the route above, all packets are routed through the given gateway 192.0.1.1, instead of going through the default gateway.
However, after we reboot our machine, the route doesn’t exist anymore. The route command above, only adds temporary routing rules. In order persist that route, we add a slightly modified line to /etc/network/interfaces (NOTE: Do not indent that line):
up route add -net 192.0.0.0/24 gw 192.0.1.1 dev eth0
Now everytime the networking daemon is up (initalized), that route is added automatically to kernel ip tables.
In order to make the newly added route take effect, we have to restart the networking daemon:
sudo invoke-rc.d networking restart
That’s it!