How to use a gateway outside of the local subnet on Linux

An interesting situation occurs when you have a very limited range of public IP addresses and want to pass all traffic through a common gateway without “wasting” a public IP on that – you may find yourself wanting to use a gateway with a private IP even through your network uses public ones.

So, in my case I was dealing with a /29 subnet, providing space for only 6 hosts, all of which were needed to host various services. The gateway, as a result of this, could not occupy one of the precious IP’s. The solution was to put the gateway on a static, but local, IP address, and create a route to it in /etc/network/interfaces.

iface eth0 inet static
    address 1.2.3.4
    netmask 255.255.255.248
    up   route add -host 172.30.0.1 dev eth0
    up   route add -net 0.0.0.0 netmask 0.0.0.0 gw 172.30.0.1 dev eth0
    down route del -net 0.0.0.0 netmask 0.0.0.0 gw 172.30.0.1 dev eth0
    down route del -host 172.30.0.1 dev eth0

While 1.2.3.4 has obviously been replaced for privacy reasons, this is pretty much the setup. The gateway is at 172.30.0.1, a private IP. Each time the interface is brought up or down, a default route to the gateway is automatically added and removed as appropriate.

Leave a Reply

Your email address will not be published. Required fields are marked *