alezzandro.com

Two ethernet, same subnet, route to two different gateways

Hi there,

I was not writing here technical tricks for a long time,

Recently I have to deal with a strange network configuration:

Two (virtual) ethernet interfaces with ip addresses on the same subnet, but that have to route packets to two different gateways.

I’ve made a schema for better explaining this kind of configuration:

So the simple way to achieve this kind of scenario is using: iptables!

ip route flush table 4
ip route flush table 5
iptables -t nat -F

iptables -t mangle -F
iptables -F

ip route add table 4 default via 192.168.241.101

ip route add table 5 default via 192.168.241.102

iptables -t mangle -A OUTPUT -p udp -s 192.168.241.98 –sport 5060 -j MARK –set-mark 4
iptables -t mangle -A OUTPUT -p udp -s 192.168.241.99 –sport 5060 -j MARK –set-mark 5

ip rule add fwmark 4 table 4
ip rule add fwmark 5 table 5

ip route flush cache

First of all we flush any previous settings in the affected tables, then we add to table 4 and table 5 the different gateways. After that we use the mangle table of ipfilter framework that let us edit packets marking them with a custom marker. In detail, we’ll mark the packets coming from a specific interface’s address and from a specific port. By the way you could enlarge this rule as much as you want, removing the port number for example.

In this case for packets marking we used the same number of the associated table but this is not mandatory!

After that we add the rule for moving all the packets we’ll mark in their respective table. Thanks to this kind of rule we ensure that every marked packet will be forwarded to the respective gateway!

That’s all folks! Have fun! :)