综合案例: 两个私有网络的互相通迅

iptables两个私有网络的互相通迅_dnat

​环境准备:​

​主机A IP地址:192.168.0.6/24(vmnet2)  网关:192.168.0.8​

​firewallA:192.168.0.8/24(vmnet2)  10.0.0.8/24 (NATvmnet8)​​​​ 提前开启ip_forward(临时开启echo 1 > /proc/sys/net/ipv4/ip_forward)或者写入配置文件vim /etc/sysctl.conf  net.ipv4.ip_forward = 1 ​

​firewallB:172.16.0.18/24(vmnet4)  10.0.0.8/24 (NATvmnet8)​

​主机B IP地址:172.16.0.7/24(vmnet4)  网关:172.16.0.18​


主机A:

​[root@internet ~]#route -n ​

​Kernel IP routing table ​

​Destination     Gateway         Genmask         Flags Metric Ref    Use Iface ​

​0.0.0.0         192.168.0.8     0.0.0.0         UG    100    0        0 eth0 ​

​192.168.0.0     0.0.0.0         255.255.255.0   U     100    0        0 eth0​

​[root@internet ~]#systemctl start nginx.service ​

主机B:

​[root@internet2 ~]#route -n ​

​Kernel IP routing table ​

​Destination     Gateway         Genmask         Flags Metric Ref    Use Iface ​

​0.0.0.0         172.16.0.18     0.0.0.0         UG    100    0        0 eth0 ​

​172.16.0.0      0.0.0.0         255.255.255.0   U     100    0        0 eth0 ​

​[root@internet2 ~]#systemctl start nginx.service​

firewallA:

​[root@firewall ~]#route del default  ​

​[root@firewall ~]#route -n ​

​Kernel IP routing table ​

​Destination     Gateway         Genmask         Flags Metric Ref    Use Iface ​

​10.0.0.0        0.0.0.0         255.255.255.0   U     100    0        0 eth0 ​

​192.168.0.0     0.0.0.0         255.255.255.0   U     101    0        0 eth1​

iptables两个私有网络的互相通迅_dnat_02

​[root@firewall ~]#iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -j MASQUERADE ​

​[root@firewall ~]#iptables -t nat -A PREROUTING -d 10.0.0.8 -p tcp --dport 80 -j DNAT --to-destination 192.168.0.6:80​

iptables两个私有网络的互相通迅_dnat_03


firewallB:

​[root@lanserver ~]#route del default​

​[root@lanserver ~]#route -n ​

​Kernel IP routing table ​

​Destination     Gateway         Genmask         Flags Metric Ref    Use Iface ​

​10.0.0.0        0.0.0.0         255.255.255.0   U     100    0        0 eth0 ​

​172.16.0.0      0.0.0.0         255.255.255.0   U     101    0        0 eth1​

iptables两个私有网络的互相通迅_snat_04

​[root@lanserver ~]#iptables -t nat -A POSTROUTING -s 172.16.0/24 -j MASQUERADE ​

​[root@lanserver ~]#iptables -t nat -A PREROUTING -d 10.0.0.28 -p tcp --dport 80 -j DNAT --to-destination 172.16.0.7:80​

iptables两个私有网络的互相通迅_iptables_05


测试:

主机A:

​[root@internet ~]#curl 10.0.0.28 ​

​welcome to 8.333333333​

主机B:

​[root@internet2 ~]#curl 10.0.0.8 ​

​welcome  192.168.0.6​


总结:

SNAT: 实现内部网络访问外部网络,将请求报文中的源地址和源端口转化成公网地址和端口

DNAT:实现外部网络访问内部网络,将请求报文中的目的地址和端口转化成内网地址和端口

REDIRECT:本机端口转发,将请求转发至本机的另一个端口