端口转发用来中转后端服务,iptables不仅支持单端口,连端口段也可以转发,同时TCP/UDP均可
特别注明:本地服务器 IP 未必是公网 IP ,像阿里云就是内网 IP ,请用 ipconfig 确认下走流量的网卡 IP 是外网还是内网。
第一步:开启系统的转发功能
nano -w /etc/sysctl.d/90-forward.conf
net.ipv4.ip_forward=1
# Enables Proxy ARP on all interfaces
net/ipv4/conf/all/proxy_arp = 1
# Enables Proxy ARP on a specific interface (Replace "interfacename"
# with your interface, eg.eth0, eth0.100, wlan0, etc.)
#net/ipv4/conf/eth0/proxy_arp = 1
第二步: iptables 的命令
完整写法
iptables -t nat -A PREROUTING -p tcp --dport [端口号] -j DNAT --to-destination [目标IP]
iptables -t nat -A PREROUTING -p udp --dport [端口号] -j DNAT --to-destination [目标IP]
iptables -t nat -A POSTROUTING -p tcp -d [目标IP] --dport [端口号] -j SNAT --to-source [本地服务器IP]
iptables -t nat -A POSTROUTING -p udp -d [目标IP] --dport [端口号] -j SNAT --to-source [本地服务器IP]
端口段写法
iptables -t nat -A PREROUTING -p tcp -m tcp –dport 50000:65535 -j DNAT –to-destination 1.1.1.1
iptables -t nat -A PREROUTING -p udp -m udp –dport 50000:65535 -j DNAT –to-destination 1.1.1.1
iptables -t nat -A POSTROUTING -d 1.1.1.1 -p tcp -m tcp –dport 50000:65535 -j SNAT –to-source [本地服务器IP]
iptables -t nat -A POSTROUTING -d 1.1.1.1 -p udp -m udp –dport 50000:65535 -j SNAT –to-source [本地服务器IP]