November 10, 2010
Recently, I wanted to assign a second public IP address to a Linux (Debian) server. First thing that came to mind was to create a network interface alias like so:
iface eth0 inet dhcp iface eth0:0 inet static address x.x.x.x (the secondary IP) gateway x.x.x.x (the secondary IP gateway) netmask x.x.x.x (the secondary IP netmask)
Creating a network interface alias makes sense because both my IP addresses are in the same subnet. Doing this worked, but it also posed a problem. I had to be able to specifiy which of my IP addresses was used for outbound connections. Here’s how.
At first I wasn’t sure how to do this, so I did a quick Google search. I found various solutions to my problem, but most of them somehow didn’t work.
One suggestion was to add a route to the kernel routing table using
ip route add default dev eth0, which was supposed to route all traffic over the eth0 device, which is assigned my preferred ip for outbound connections. I’m not sure why this didn’t work, maybe because the
eth0:0 network interface is also bound to the
Another suggestion was to specify a gateway only for the interface you want to have outbound traffic routed to, like this:
iface eth0 inet dhcp iface eth0:0 inet static address x.x.x.x (the secondary IP)
gateway x.x.x.x (the secondary IP gateway)netmask x.x.x.x (the secondary IP netmask)
Unfortunately, this didn’t work either.
Finally I found this page on the Linode wiki which had a solution that actually worked for me:
iface eth0 inet dhcp up /sbin/ip addr add the.secondary.ip.here/24 dev eth0
This should basically do about the same as binding the ip to a network device alias without specifying a gateway. The only difference is that using an alias you basically create a virtual network device, while using the method above you just bind the ip to the existing physical network device. I’m not sure in what way this is exactly different in regard of the IP address used for outbound connections.
If anyone can explain the difference between solution #2 and #3 please do so in the comments below.