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
    up   route add -host dev eth0
    up   route add -net netmask gw dev eth0
    down route del -net netmask gw dev eth0
    down route del -host dev eth0

While has obviously been replaced for privacy reasons, this is pretty much the setup. The gateway is at, 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 *