System can have only one gateway at the moment. Only can you do is to force some traffic aka ssh, ftp, .. or to specific network to go on different interface
Route traffic to specific port via specific interface
Example:
Here we shall take port 4444
as the service for routing. Use mangle
table of iptables for modifying the 4444
packets.
sudo iptables -t mangle -A OUTPUT -p tcp –dport 4444 -j MARK –set-mark 0×1
We are marking all packets with destination port 4444
as ’0×1′ .
To delete this entry from iptables
we can use -D
instead of -A
.
Next, create a new IP route table in /etc/iproute2/rt_table
by just giving an entry
100 4444table
Write rule for 4444
packets.
ip rule add fwmark 0×1 lookup 4444table
Add route at new table 4444table
. Here we shall use ’192.168.1.1′ as the gateway for 4444
.
We copy all entries except default gateway entry from main table.
sudo ip route show table main | grep -Ev ^default | while read ROUTE ; do ip route add table 4444table $ROUTE; done
Add default gateway entry for 4444
packets to table 4444table
sudo ip route add default via 192.168.1.1 table 4444table
Use ip route show table 4444table
to show all routes at 4444table
.
Or routing by destination
Destination ip 132.45.65.60
Again use mangle table of iptables
for modifying the packets for 132.45.65.60
sudo iptables -t mangle -A OUTPUT -d 132.45.65.60 -j MARK -set-mark 0×1
We are marking all packets router to ip 132.45.65.60
as ’0×1′ .
Now save and restart iptables
.
service iptables save
service iptables restart
Next, create a new IP route table in /etc/iproute2/rt_tables
by just giving an entry
100 132table
Write rule for packets to destination ip 132.45.65.60
ip rule add fwmark 0×1 lookup 132table
Add route at new table 132table
. Here we shall use 192.168.1.1
. All other traffic will go through the default gateway.
Copy all entries except default gateway entry from main table.
sudo ip route show table main | grep -Ev ^default | while read ROUTE ; do ip route add table 132table $ROUTE; done
Add default gateway entry for 132.45.65.60 packets to table 132table
sudo ip route add default via 192.168.1.1 table 132table
Edit 1
If you have to set metric
aka with metric
interface without metric have "priority"
auto eth0
iface eth0 inet static
address 192.168.1.202
netmask 255.255.255.0
gateway 192.168.1.1
auto eth1
iface eth1 inet static
address 10.10.0.10
netmask 255.255.255.0
gateway 10.10.0.1
metric 800
With this setup if available default gateway will be 192.168.1.1
and traffic will go trough eth0
. When you do ifdown eth0
or disconnect cable from eth0
, second best will be gateway 10.10.0.1
with metric 800
and traffic will go trough eth1
. When you connect cable or ifup eth0
default gw will be again 192.168.1.1
.
Like I say.
System can not have two default gateways in one moment. If have network will not work.