Shell Script to Route Multiple Public/Private Interfaces

If you have a server with multiple interfaces – either public and/or private – your routing table might look something like this:

This example shows one private interface with IP, two public interfaces with IPs and, and a default route to This means that any traffic to/from an IP outside the interface’s subnets is sent to — and this is where problems occur (and probably why you’re reading this article). ;-)

In this example, you have two public interfaces, each (in theory) capable of receiving traffic from the internet, but any IP falling outside of their subnets is sent to For example, a client connects from IP to IP on this server. Since is not within subnet, the reply is sent to, *which is on the wrong interface*. If you want to route each interface properly (sending traffic back out the way it came), you have to setup multiple routing tables, each with it’s own default gateway.

Using the same example, you might create three routing tables; an “intern” table for eth0, a “prov_1” table for eth1, and a “prov_2” table for eth2. Here’s what the creation of those tables might look like:

With these rules in place, network traffic from a client with IP, connecting to IP, will be sent to the “prov_2” table, which will have the proper default gateway for that interface. The result is that traffic coming in on one interface will go back out on the same interface, to the correct default gateway IP.

Using and “prov_2” as an example, the routing table itself might look like this:

If you have just one server with multiple interfaces, and those interfaces and subnets never change, then you could simply add these ip rule/route commands to a startup script (right after networking starts), or you could use the following script. It will create the proper rules and routes for multiple networks, no matter which interface they are on (including virtual interfaces).

The script depends on /bin/bash and the ipcalc binary (available on most, if not all distributions). The top-most section of the script must be configured for your network.

The configuration is fairly self-explanatory — an rt_tables array defines the routing table numbers and names used in the /etc/iproute2/rt_tables file, each case statement line defines the gateway for that network/netmask, its metric (in case you use multiple default gateways in the same table), the table name, the rule priority (see the ip rule list command), and if forwarding should be turned on or off for that interface.

Download the script here, or click on the “Copy plain Code” or “Open Code in New Window” symbol to copy-paste the script.

Find this content useful? Share it with your friends!