Purpose

  • Monitor the local port 7777 and forward the data to the 8888 port of 192.168.7.8 to realize TCP data forwarding.

Method one ncat

  • ncat port forwarding, common to Linux/Windows
 ncat --sh-exec "ncat 192.168.7.8 8888" -l 7777 --keep-open

Method 2 netsh (Windows)

 #将本机 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
  • Check
 netsh interface portproxy show all
  • remove
 netsh interface portproxy delete v4tov4 listenport=7777 listenaddress=0.0.0.0

Method three iptables (Linux)

 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
  • Enable port forwarding (/etc/sysctl.conf)
 # 开启端口转发
sudo sysctl net.ipv4.ip_forward=1
# 查看
sudo sysctl -a | grep ip_forward
  • Configure port forwarding
 # 转发规则配置(可添加详细的限制规则)
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
 # tap0 为转发出口网卡代号
# 本例为 tap 虚拟网卡
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
  • remove example
 # 查看
sudo iptables -t nat -nL --line-numbers
# 移除。最后的数字为加 --line-numbers 参数后 num 显示的序号
sudo iptables -t nat -D POSTROUTING 1
  • port view
 sudo netstat -anpt | grep 7777

It can be seen that the connection forwarded by the iptables port cannot be viewed with netstat, because NAPT does not need to occupy the port, and port 7777 can still be used by other programs. To check, you can use netstat-nat or conntrack command.

 conntrack -L -p tcp --src-nat
# OR
conntrack -L -n
  • Why does NAPT not occupy ports: iptables works on the 2/3/4 layers of the OSI model. When doing port forwarding, you only need to view and convert the port number of the transport layer, and do not need to occupy it. The following is excerpted from "Computer Networks (5th Edition)" (Xie Xiren) 175 pages.
 应当指出,从层次的角度看,NAPT 的机制有些特殊。
普通路由器在转发 IP 数据报时,对于源 IP 地址或目的 IP 地址都是不改变的。但 NAT 路由器在转发 IP 数据报时,一定要更换其 IP 地址(转换源 IP 地址或目的 IP 地址)。
其次,普通路由器在转发分组是,是工作在网络层。但 NAPT 路由器还要查看和转换运输层的端口号,而这本来应当属于运输层的范畴。也正因为这样,NAPT 曾遭受一些人的批评,认为 NAPT 的操作没有严格按照层次的关系。
This article is from qbit snap

qbit
268 声望279 粉丝

引用和评论

0 条评论