我正在设置一台具有 2 个网络接口的服务器,每个接口都有其 IP 地址。我有 2 个不同的程序在端口 8080 上监听(每个程序在每个 IP 地址上),我正在使用 iptables 将流量从端口 80 重定向到 8080。
问题是我无法从另一台计算机实际连接到 eth1 的 IP 地址。如果我从同一台服务器尝试,它会按预期工作,但从其他计算机连接会超时。我猜 iptables 将所有流量发送到 eth0,并且因为没有程序在该接口上监听该 IP,所以连接超时,但我真的不知道如何修复它。
这是我的网络配置的输出:
→ sudo iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
REDIRECT tcp -- anywhere anywhere tcp dpt:https redir ports 8443
REDIRECT tcp -- anywhere anywhere tcp dpt:http redir ports 8080
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
→ ip route
default via 172.31.16.1 dev eth0
172.31.16.0/20 dev eth0 proto kernel scope link src 172.31.21.84
172.31.16.0/20 dev eth1 proto kernel scope link src 172.31.26.28
→ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 172.31.16.1 0.0.0.0 UG 0 0 0 eth0
172.31.16.0 0.0.0.0 255.255.240.0 U 0 0 0 eth0
172.31.16.0 0.0.0.0 255.255.240.0 U 0 0 0 eth1
→ ifconfig
eth0 Link encap:Ethernet HWaddr 02:bb:c3:cc:8b:47
inet addr:172.31.21.84 Bcast:172.31.31.255 Mask:255.255.240.0
inet6 addr: fe80::bb:c3ff:fecc:8b47/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:9001 Metric:1
RX packets:6300 errors:0 dropped:0 overruns:0 frame:0
TX packets:5564 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1095572 (1.0 MB) TX bytes:1064691 (1.0 MB)
eth1 Link encap:Ethernet HWaddr 02:71:e7:b4:bc:52
inet addr:172.31.26.28 Bcast:172.31.31.255 Mask:255.255.240.0
inet6 addr: fe80::71:e7ff:feb4:bc52/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:9001 Metric:1
RX packets:238 errors:0 dropped:0 overruns:0 frame:0
TX packets:11 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:11236 (11.2 KB) TX bytes:1422 (1.4 KB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:63 errors:0 dropped:0 overruns:0 frame:0
TX packets:63 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1
RX bytes:43236 (43.2 KB) TX bytes:43236 (43.2 KB)
答案1
我认为您需要为 2 个 NIC 创建单独的规则。我会尝试以下方法:
$ sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
$ sudo iptables -A PREROUTING -t nat -i eth1 -p tcp --dport 80 -j REDIRECT --to-port 8080
$ sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443
$ sudo iptables -A PREROUTING -t nat -i eth1 -p tcp --dport 443 -j REDIRECT --to-port 8443
答案2
我必须按照 slm 的说法为 iptables 添加单独的规则,而且我必须为每个接口的规则使用 2 个查找表,如下所示:
sudo ip route add default via 172.31.16.1 dev eth0 tab 1
sudo ip route add default via 172.31.16.1 dev eth1 tab 2
sudo ip rule add from 172.31.21.84/32 tab 1
sudo ip rule add from 172.31.26.28/32 tab 2