端口轉發(Linux/Windows)

【目的】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 windowsbash

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 IPtableside

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的流水帳 ***

相關文章
相關標籤/搜索