Linux – Specifying source IP address for a host route

linuxrouterouting

I am using Ubuntu 12.04. I assigned two IP addresses to the ethernet card by editing /etc/network/interfaces. It now looks like that (skipping lines not related to the question).

auto eth0
iface eth0 inet static
    address 192.168.60.23
    netmask 255.255.255.0
    gateway 192.168.60.1
    up route add 192.168.60.1 dev eth0
    up route add 10.0.1.1 dev eth0
    up route add 192.168.60.151 gw 10.0.1.1

auto eth0:1
iface eth0:1 inet static
    address 192.168.60.101
    netmask 255.255.255.0

Now, howerver, I would like to let the packets going to 192.168.60.151 leave my machine with the second IP address (192.168.60.101) as source address.

I tried adding src 192.168.60.101 to the corresponding up route line but it didn't work. I also tried to move this line to the eth0:1 block but it didn't work either. When I execute ip route get 192.168.60.151 I always get 192.168.60.151 via 10.0.1.1 dev eth0 src 192.168.60.21.

I googled but didn't find out how to modify the source address of outgoing packets.

Best Answer

This should work. It is using ip(8) syntax instead of route(8), but else equivalent. The route to 192.168.60.151 must be set on the second interface definition, or else the src address is not yet set and the command fails.

auto eth0
iface eth0 inet static
    address 192.168.60.23
    netmask 255.255.255.0
    gateway 192.168.60.1
    # The next line should not be necessary, the target is on the same subnet and link
    # up ip route add 192.168.60.1 dev eth0
    up ip route add 10.0.1.1 dev eth0

auto eth0:1
iface eth0:1 inet static
    address 192.168.60.101
    netmask 255.255.255.0
    # ip(8) uses 'via' instead of 'gw'
    up ip route add 192.168.60.151 via 10.0.1.1 src 192.168.60.101