xxxmenger 发表于 2018-6-15 10:11:39

端口转发(Linux/Windows)

  【目的】
  监听本机 7777 端口,将数据转发到 192.168.7.8 的 8888 端口,实现 TCP 数据转发。
  【方法】
  1、ncat(Linux/Windows 通用)(ncat端口转发)
ncat --sh-exec "ncat 192.168.7.8 8888" -l 7777 --keep-open  
  2、netsh(Windows)(port forwarding in windows)
  2.1、设置
#将本机 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.2、查看
netsh interface portproxy show all  2.3、移除
netsh interface portproxy delete v4tov4 listenport=7777 listenaddress=0.0.0.0  3、iptables(Ubuntu 16.04)(How-To: Redirecting network traffic to a new IP using IPtables)
  3.1、清空规则
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.2、开启端口转发(/etc/sysctl.conf)
# 开启端口转发  
sudo sysctl net.ipv4.ip_forward=1
  
# 查看
  
sudo sysctl -a | grep ip_forward
  3.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、移除示例
#查看  
sudo iptables -t nat -nL --line-numbers
  
#移除。最后的数字为加 --line-numbers 参数后 num 显示的序号
  
sudo iptables -t nat -D POSTROUTING 1
  3.4、端口查看
sudo netstat -anpt | grep 7777  可以看到 iptables 端口转发的连接并不能用 netstat 查看,因为 NAPT 并不需要占用端口(为啥?),7777 端口仍然可以被其它程序使用。若需查看,可使用 netstat-nat 命令。
  相关阅读:
  1、网络端口的转发和重定向(Python)
  2、Windows 和 Linux 平台下的端口转发工具
  3、简单的TCP代理服务器
  4、centos6.5 iptables实现端口转发
  *** walker的流水账 ***
页: [1]
查看完整版本: 端口转发(Linux/Windows)