Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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