Search code examples
iptables

iptables forward specific port to specific nic


what I have in my ubuntu is:

eth0(local) = 192.168.1.1/24 attemp to be gateway for local network
eth1(net1) = 192.168.2.2/24 gateway is 192.168.2.1 is a DSL 1
eth2(net2) = 192.168.3.2/24 gateway is 192.168.3.1 is a DSL 2

what I want is:

port 22,53,80,443 force to use only through eth1
port 6881 to 6889 and other ports force to use only through eth2

How to make rules in iptables?

Thank you.


Solution

  • Mark packages which should go via eth1:

    iptables -A PREROUTING -i eth0 -t mangle -p tcp --dports 22,53,80,443 -j MARK --set-mark 1
    

    Add rule eth1.out to route marked packages:

    echo "201 eth1.out" >> /etc/iproute2/rt_tables
    ip rule add fwmark 1 table eth1.out
    

    Route all marked packages via eth1:

    /sbin/ip route add default via 192.168.2.1 dev eth1 table eth1.out
    

    Route everything else via eth2:

    /sbin/ip route add default via 192.168.3.1 dev eth2 
    

    If MARK rule won't work, try using CONNMARK.