Skip to content

Instantly share code, notes, and snippets.

@iflamed
Last active October 30, 2018 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iflamed/aa047530d5e8baf44592668ccb2d9785 to your computer and use it in GitHub Desktop.
Save iflamed/aa047530d5e8baf44592668ccb2d9785 to your computer and use it in GitHub Desktop.
iptables 端口转发、中继上网

开启防火墙的ipv4转发

echo -e "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

配置iptables开机加载

首先我们设置一下iptables 防火墙的开机启动自动载入规则功能。

CentOS 系统:

service iptables save
chkconfig --level 2345 iptables on

Debian/Ubuntu 系统:

iptables-save > /etc/iptables.up.rules
echo -e '#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules' > /etc/network/if-pre-up.d/iptables
chmod +x /etc/network/if-pre-up.d/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]

以下示例,假设你的国外服务器(被中转服务器)是 1.1.1.1 ,你的数据接受端口是 10000 ,而你这台正在操作的VPS的主网卡绑定IP(中转服务器)是 2.2.2.2 。

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 10000 -j DNAT --to-destination 1.1.1.1:10000
iptables -t nat -A PREROUTING -p udp -m udp --dport 10000 -j DNAT --to-destination 1.1.1.1:10000
iptables -t nat -A POSTROUTING -d 1.1.1.1 -p tcp -m tcp --dport 10000 -j SNAT --to-source 2.2.2.2
iptables -t nat -A POSTROUTING -d 1.1.1.1 -p udp -m udp --dport 10000 -j SNAT --to-source 2.2.2.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment