1.在网络组建或者服务器搭建过程中,很多时候我们都需要用Linux系统的NAT转发功能,下面我就来介绍下如何使用NAT转发,以实验案例来说明。
2.网络拓扑图
3.环境介绍:
centos 6主机一台,双网卡,双网段
4.配置网络:
[[email protected] ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=dhcp
[[email protected] ~]#
[[email protected] ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1
DEVICE=eth1
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=static
IPADDR=192.168.66.1
NETMASK=255.255.255.0
[[email protected] ~]# service network restart
[[email protected] ~]# ifconfig -a
eth0 Link encap:Ethernet HWaddr 00:0C:29:37:00:93
inet addr:172.16.20.183 Bcast:172.16.255.255 Mask:255.255.0.0
eth1 Link encap:Ethernet HWaddr 00:0C:29:37:00:9D
inet addr:192.168.66.1 Bcast:192.168.66.255 Mask:255.255.255.0
[[email protected] ~]# vim /etc/sysctl.conf
net.ipv4.ip_forward = 1
让其立马生效:[[email protected] ~]# sysctl -p
6.设定转发规则:
[[email protected] ~]# iptables -t nat -A POSTROUTING -s 192.168.66.0/24 -j SNAT --to 172.16.20.183 #出口为静态IP选这个
[[email protected] ~]# iptables -t nat -A POSTROUTING -s 192.168.66.0/24 -o eth0 -j MASQUERADE #出口为动态IP选这个
查看转发规则:
配置到此就结束了,下面我们进行验证:
7.在192.168.66/24网段内的一台Linux主机设置网络如下:
[[email protected] ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=static
IPADDR=192.168.66.2
NETMASK=255.255.255.0
GATEWAY=192.168.66.1
DNS1=180.76.76.76.76
DNS2=8.8.8.8
重启网络服务
[[email protected] ~]# service network restart
Shutting down interface eth0: [ OK ]
Shutting down loopback interface: [ OK ] 8.测试:
ping 自己测试
[[email protected] ~]# ping 192.168.66.2
PING 192.168.66.2 (192.168.66.2) 56(84) bytes of data.
64 bytes from 192.168.66.2: icmp_seq=1 ttl=64 time=0.042 ms
ping网关测试
[[email protected] ~]# ping 192.168.66.1
PING 192.168.66.1 (192.168.66.1) 56(84) bytes of data.
64 bytes from 192.168.66.1: icmp_seq=1 ttl=64 time=0.261 ms
ping nat出口测试
[[email protected] ~]# ping 172.16.20.183
PING 172.16.20.183 (172.16.20.183) 56(84) bytes of data.
64 bytes from 172.16.20.183: icmp_seq=1 ttl=64 time=0.280 ms
ping nat外的工作机
[[email protected] ~]# ping 172.16.20.245
PING 172.16.20.245 (172.16.20.245) 56(84) bytes of data.
64 bytes from 172.16.20.245: icmp_seq=1 ttl=63 time=2.39 ms
ping 百度DNS
[[email protected] ~]# ping 180.76.76.76
PING 180.76.76.76 (180.76.76.76) 56(84) bytes of data.
64 bytes from 180.76.76.76: icmp_seq=1 ttl=52 time=10.2
ping 网易163
[[email protected] ~]# ping www.163.com
PING 1stcncloud163.xdwscache.ourwebpic.com (114.80.143.193) 56(84) bytes of data.
64 bytes from 114.80.143.193: icmp_seq=1 ttl=55 time=9.58 ms
ping 淘宝网
[[email protected] ~]# ping www.taobao.com
PING www.taobao.com.danuoyi.tbcache.com (114.80.174.46) 56(84) bytes of data.
64 bytes from 114.80.174.46: icmp_seq=1 ttl=48 time=8.83 ms
更多详情参考:http://www.linuxidc.com/Linux/2017-07/145382.htm