How to set the “default route” when an interface has multiple IPs

awsiprouting

I've followed this guide for Multiple IP addresses on Amazon EC2 and have gone with the second method listed of adding two IP addresses to a single interface. This was done by adding two private IPs to the adapter and then associating an elastic IP with each of the private addresses.

When I run a command like curl it uses the primary IP address and I would like to know how to change it to use the other IP address by default. Here is the setup:

Public (elastic) IPs

54.140.250.140
54.81.231.80

Private IPs

172.30.0.50
172.30.0.122

After adding the elastic and private IPs I do this:

ip addr add dev eth0 172.30.0.122/24

To confirm it's working I can do:

curl icanhazip.com
54.81.231.80

curl --interface 172.30.0.50 icanhazip.com
54.81.231.80

curl --interface 172.30.0.122 icanhazip.com
54.140.250.140

As you can see the default route is done via the original / primary IP.

Here is the data from running ifconfig

eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
          inet addr:172.30.0.50  Bcast:172.30.0.255  Mask:255.255.255.0
          inet6 addr: aabb::cccc:dddd:eeee:ffff/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
          RX packets:713 errors:0 dropped:0 overruns:0 frame:0
          TX packets:631 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:63726 (63.7 KB)  TX bytes:827217 (827.2 KB)

lo        .... omitted ....

And this is what I get from running route

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.30.0.1      0.0.0.0         UG    0      0        0 eth0
172.30.0.0      *               255.255.255.0   U     0      0        0 eth0

I tried changing the 'default' route with a script like this. I used screen so that the script would continue after I get disconnected (guessing that the first line causes that):

/sbin/route del default
/sbin/route add default via 172.30.0.122 dev eth0 tab 1

I also tried without the tab 1 but still had no luck.

How can I set what outgoing IP is used 'by default' ?

I would also like to know if it is possible to specify that only traffic to a certain range of IPs use the secondary address as the default address.

Best Answer

ip route replace default via 172.30.0.1 src 172.30.0.122
Related Question