【目的】html
监听本机 7777 端口,将数据转发到 192.168.7.8 的 8888 端口,实现 TCP 数据转发。ubuntu
【方法】windows
一、ncat(Linux/Windows 通用)(ncat端口转发)centos
ncat --sh-exec "ncat 192.168.7.8 8888" -l 7777 --keep-open
二、netsh(Windows)(port forwarding in windows)bash
2.一、设置
服务器
#将本机 7777 端口收到的内容转发到 192.168.7.8 的 8888 端口 netsh interface portproxy add v4tov4 listenport=7777 listenaddress=0.0.0.0 connectport=8888 connectaddress=192.168.7.8
2.二、查看网络
netsh interface portproxy show all
2.三、移除tcp
netsh interface portproxy delete v4tov4 listenport=7777 listenaddress=0.0.0.0
三、iptables(Ubuntu 16.04)(How-To: Redirecting network traffic to a new IP using IPtables)ide
3.一、清空规则工具
sudo iptables -F sudo iptables -X sudo iptables -t nat -F sudo iptables -t nat -X sudo iptables -t mangle -F sudo iptables -t mangle -X sudo iptables -P INPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -P OUTPUT ACCEPT
3.二、开启端口转发(/etc/sysctl.conf)
# 开启端口转发 sudo sysctl net.ipv4.ip_forward=1 # 查看 sudo sysctl -a | grep ip_forward
3.三、配置端口转发
# 转发规则配置(可添加详细的限制规则) sudo iptables -t nat -A PREROUTING -p tcp --dport 7777 -j DNAT --to-destination 192.168.7.8:8888 sudo iptables -t nat -A POSTROUTING -j MASQUERADE # 查看 sudo iptables -t nat -nL
3.3.一、MASQUERADE 在 Ubuntu 18.04 下可能引发 dns 服务异常,参见 How to allow DNS lookup with iptables on Ubuntu 18.04 server,可改为以下配置:
# tap0 为转发出口网卡代号 # 本例为 openVPN 虚拟网卡 iptables -t nat -A POSTROUTING -o tap0 -j MASQUERADE # OR (192.168.7.1 为虚拟网卡地址) iptables -t nat -A POSTROUTING -o enp4s0 -j SNAT --to-source 192.168.7.1
3.三、移除示例
#查看 sudo iptables -t nat -nL --line-numbers #移除。最后的数字为加 --line-numbers 参数后 num 显示的序号 sudo iptables -t nat -D POSTROUTING 1
3.四、端口查看
sudo netstat -anpt | grep 7777
能够看到 iptables 端口转发的链接并不能用 netstat 查看,由于 NAPT 并不须要占用端口(为啥?),7777 端口仍然能够被其它程序使用。若需查看,可以使用 netstat-nat 命令。
【相关阅读】
*** walker的流水帐 ***