How to Add a Routing Rule that Only Matches ‘dport’ in iptables

ip-routingiproute2iptablesopenwrtrules

In my OpenWrt box, I want to route only a specific protocol(tcp:1888) to a tun interface only for one PC(192.168.28.2), so I do as following:

ip rule add from 192.168.28.2 dport 1888 lookup 123

ip route add default via 10.8.0.2 dev tun0 table 123

But it does NOT work!

When I check the rule list with ip rule, I get:

0: from all lookup local

32765: from 192.168.28.2 lookup 123

32766: from all lookup main

32767: from all lookup default

I guest that the dport SELECTOR doesn't take effect.

How should I do?

Thanks!!!

Solution:
With Nikita Kipriyanov's help, I got it, but the FORWARD chain of mangle table doesn't work, I used the PREROUTING instaed.

Would pls anyone explain why should I use PREROUTING instead of FORWARD of mangle?

Best Answer

Add a netfilter mark rule in the FORWARD chain of the mangle table. Then add a routing rule using that mark:

iptables -t mangle -A PREROUTING -s 192.168.28.2 -p tcp --dport 1888 -j MARK --set-mark 0x1/0x1
ip rule add fwmark 0x1/0x1 lookup 123
Related Topic