Route IP through virtual interface

5

3

On Linux, is it possible to have all requests done to a specific IP to be routed through a virtual interface, so that on the other end they appear with a different IP address that the host's main? Suppose that eth0 has the IP address 1.1.1.1 while eth0:1 has the address 1.1.1.2. How can I make all requests to 1.2.3.4 appear as coming from eth0:1? I am trying the following but it doesn't seem to work:

route add 1.2.3.4 dev eth0:1

Georgios Gousios

Posted 2013-02-08T16:49:23.873

Reputation: 153

Answers

6

Yes.

One way to do this would be to use IPTABLES to rewrite the packets leaving the machine with multiple IP addresses to say they come from the virtual interface. Try

/sbin/iptables -t nat -I POSTROUTING -d DEST.IP -j SNAT --to VIRTUAL.IP

(You do, of-course, need to have the virtual IP set up as you contemplated, ie eth0:1 or equivalent needs to exist so traffic can find its way back to the machine)

davidgo

Posted 2013-02-08T16:49:23.873

Reputation: 49 152

2

It may be necessary to use the command

ip route add 1.2.3.4 dev eth0:1 src 1.1.1.2

or route with a similar option. If that does not work as expected you may need advanced routing: Create an additional routing table for this target in /etc/iproute2/rt_tables, put the above entry as the only one into this table and activate this table:

ip rule add to 1.2.3.4 priority 100 table to__1_2_3_4
ip route flush cache

The desperate last resort solution would be netfilter: You could use SNAT with iptables in the POSTROUTING chain to rewrite the source address for packets to this destination.

Hauke Laging

Posted 2013-02-08T16:49:23.873

Reputation: 275

Fortunately I could use the first command (ip route add with src option) – YudhiWidyatama – 2019-01-15T23:04:59.027

Unfortunately, I had to resort to SNAT (see answer above), tuning IP routing tables is not my strong point :-) Thanks! – Georgios Gousios – 2013-02-08T19:16:46.487