使用 iptables 进行端口转发 -> 连接被拒绝

使用 iptables 进行端口转发 -> 连接被拒绝

我正在尝试将对本地 IP (10.42.42.152) 端口 80 的请求重定向到远程服务器,例如 google.com (173.194.113.104:80)。远程服务器已启动,ip_forward 已启用,但我只收到“连接被拒绝”的消息。

root@raspi:~# telnet 10.42.42.152 80
Trying 10.42.42.152...
telnet: Unable to connect to remote host: Connection refused

显示ip转发已启用:

root@raspi:~# cat /proc/sys/net/ipv4/ip_forward
1

以下是我的默认 iptables 规则:

# /etc/iptables.up.rules
# Generated by iptables-save v1.4.14 on Fri Sep 26 10:22:12 2014
*filter
:INPUT ACCEPT [8542:1505054]
:FORWARD ACCEPT [476:105829]
:OUTPUT ACCEPT [6274:968245]
COMMIT
# Completed on Fri Sep 26 10:22:12 2014
# Generated by iptables-save v1.4.14 on Fri Sep 26 10:22:12 2014
*nat
:PREROUTING ACCEPT [533:70053]
:INPUT ACCEPT [491:65475]
:OUTPUT ACCEPT [685:60069]
:POSTROUTING ACCEPT [683:59949]
-A INPUT -i eth0 -p udp -m udp --dport 1194 -j ACCEPT
-A POSTROUTING -s 10.8.0.0/24 -o eth0 -j SNAT --to-source 10.42.42.4
COMMIT
# Completed on Fri Sep 26 10:22:12 2014

加载这些规则(仅适用于我的 VPN),然后添加另外两个规则:

root@raspi:~# iptables-restore < /etc/iptables.up.rules
root@raspi:~# /sbin/iptables -t nat -A PREROUTING -p tcp --dport 80 -d 10.42.42.152 -j DNAT --to-destination 173.194.113.104:80
root@raspi:~# /sbin/iptables -t nat -A POSTROUTING -p tcp --dport 80 -j MASQUERADE

显示IP地址10.42.42.152属于本地设备:

root@raspi:~# ip address show eth0 | grep 152
    inet 10.42.42.152/24 brd 10.42.42.255 scope global secondary eth0:152

root@raspi:~# ping 10.42.42.152 -c 1
PING 10.42.42.152 (10.42.42.152) 56(84) bytes of data.
64 bytes from 10.42.42.152: icmp_req=1 ttl=64 time=0.347 ms
--- 10.42.42.152 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.347/0.347/0.347/0.000 ms

答案1

配置按原样工作,但不适用于本地请求。因此,如果网络中的某个其他主机(例如来自 10.42.42.15)尝试连接,则一切都应按预期工作。

对于来自本地主机的连接我发现https://unix.stackexchange.com/a/113651

只需添加:

/sbin/iptables -t nat -A OUTPUT -p tcp --dport 80 -d 10.42.42.152 -j DNAT --to-destination 173.194.113.104:80

相关内容