iptables将特定端口转发到特定的nic

时间:2011-03-08 10:34:57

标签: iptables

我在ubuntu中拥有的是:

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

我想要的是:

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

如何在iptables中制定规则?

谢谢。

2 个答案:

答案 0 :(得分:1)

标记应通过eth1的包裹:

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

添加规则eth1.out以路由标记的包:

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

通过eth1路由所有标记的包:

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

通过eth2路由其他所有内容:

/sbin/ip route add default via 192.168.3.1 dev eth2 

如果MARK规则不起作用,请尝试使用CONNMARK

答案 1 :(得分:1)

我需要在我的覆盆子pi 3模型b上移植到另一个ip地址,这就是我完成它的方式。

sudo vi /etc/sysctl.conf

并取消该行

net.ipv4.ip_forward=1

重新加载sysctl或重新启动raspberry pi

sudo sysctl -p /etc/sysctl.conf

然后运行以下iptables命令

iptables -t nat -A PREROUTING -i eth1-p tcp --dport 22 -j DNAT --to-destination 192.168.0.198:22
iptables -t nat -A PREROUTING -i eth1-p tcp --dport 53 -j DNAT --to-destination 192.168.0.198:53
iptables -t nat -A PREROUTING -i eth1-p tcp --dport 80 -j DNAT --to-destination 192.168.0.198:80
iptables -t nat -A PREROUTING -i eth1-p tcp --dport 443 -j DNAT --to-destination 192.168.0.198:443

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE