学无止境linuxiptables配置内网转发保留源ip的方法
Riv3n前提
这里假设我们配置iepl内网转发
国内端IP为:114.114.114.114 内网IP为: 10.0.0.1/24
国外端IP为:1.1.1.1 内网为:10.0.0.2/24
请同时在双端执行如下命令:
1 2
| echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf sysctl -p
|
保留源ip转发
CentOS
在国外端执行:
1
| iptables -t nat -A POSTROUTING -j MASQUERADE
|
国内端执行:
1 2 3 4 5 6 7
| ip ro change default via 10.0.0.2 yum install iptables-services -y iptables -t nat -A PREROUTING -d 114.114.114.114 -p tcp -m tcp --dport 23:65535 -j DNAT --to-destination 10.0.0.2 iptables -t nat -A PREROUTING -d 114.114.114.114 -p udp -m udp --dport 23:65535 -j DNAT --to-destination 10.0.0.2 service iptables save chkconfig iptables on reboot
|
随后在国外端执行如下命令:
1 2 3
| echo 'from 10.0.0.0/24 lookup 101' > /etc/sysconfig/network-scripts/rule-eth1 echo 'default via 10.0.0.1 table 101' > /etc/sysconfig/network-scripts/route-eth1 reboot
|
注意这里的eth1为你系统实际的网卡名
重启完成后 双端转发设置完成
Debian&Ubuntu
在国外端执行:
1
| nano /etc/network/interfaces
|
在eth1即内网网卡的配置下增加
1 2
| up ip ru add from 10.0.0.0/24 lookup 101 up ip ro add default via 10.0.0.1 table 101
|
保存配置后 重启网络
国内端执行:
1 2 3 4 5
| echo '#!/bin/bash iptables -t nat -A PREROUTING -d 114.114.114.114 -p tcp -m tcp --dport 23:65535 -j DNAT --to-destination 10.0.0.2 iptables -t nat -A PREROUTING -d 114.114.114.114 -p udp -m udp --dport 23:65535 -j DNAT --to-destination 10.0.0.2'> /etc/network/if-pre-up.d/pre-iptables chmod +x /etc/network/if-pre-up.d/pre-iptables reboot
|
不保留源ip转发
CentOS
在国外端执行:
1
| iptables -t nat -A POSTROUTING -j MASQUERADE
|
国内端执行:
1 2 3 4 5 6 7 8
| ip ro change default via 10.0.0.2 yum install iptables-services -y iptables -t nat -A POSTROUTING -j MASQUERADE iptables -t nat -A PREROUTING -d 114.114.114.114 -p tcp -m tcp --dport 23:65535 -j DNAT --to-destination 10.0.0.2 iptables -t nat -A PREROUTING -d 114.114.114.114 -p udp -m udp --dport 23:65535 -j DNAT --to-destination 10.0.0.2 service iptables save chkconfig iptables on reboot
|
随后在国外端执行如下命令:
重启完成后 双端转发设置完成
Debian&Ubuntu
国内端执行:
1 2 3 4 5 6
| echo '#!/bin/bash iptables -t nat -A POSTROUTING -j MASQUERADE iptables -t nat -A PREROUTING -d 114.114.114.114 -p tcp -m tcp --dport 23:65535 -j DNAT --to-destination 10.0.0.2 iptables -t nat -A PREROUTING -d 114.114.114.114 -p udp -m udp --dport 23:65535 -j DNAT --to-destination 10.0.0.2'> /etc/network/if-pre-up.d/pre-iptables chmod +x /etc/network/if-pre-up.d/pre-iptables reboot
|
设置完成