CentOS Linux 开启 IP 路由转发和 NAT

如果我们想把 CentOS Linux 当做路由器来使用,那么我们需要开启 CentOS Linux 的 IP 路由转发和 NAT 功能,具体如下所示:

1 、请确保您的服务器已开启对英特尔虚拟化技术的支持,该配置需要在 BIOS 里更改,详情请点击这里

2 、开启 IP 路由转发:

( 1 )临时开启(配置写入内存,立即生效,重启服务器后失效):

[root@host ~]# echo "1" > /proc/sys/net/ipv4/ip_forward

( 2 )永久开启(配置写入硬盘,执行命令 sysctl -p 后生效,同时重启服务器后还会生效):

[root@host ~]# echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
[root@host ~]# sysctl -p

( 3 )可使用下列命令查看是否开启:

[root@host ~]# sysctl -a | grep "ip_forward"
net.ipv4.ip_forward = 1
[root@host ~]#

3 、开启 NAT :

[root@host ~]# iptables -t nat -F    # 清除原有的 NAT 表中的规则
[root@host ~]# iptables -F    # 清除原有的 filter 表中的规则
[root@host ~]# iptables -P FORWARD ACCEPT    # 缺省允许 IP 转发

# 利用 iptables 实现 NAT MASQUERADE 共享上网,此处 eth0 需要是能够访问外部网络的网卡接口
[root@host ~]# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

4 、如需查看现有 NAT 表中有哪些规则,请使用如下命令查看:

[root@host ~]# iptables -t nat -L

5 、其他服务器只需要将网关设置为上述开启了 IP 路由转发和 NAT 的服务器即可,例如:

[root@host ~]# sed -i "/GATEWAY=/d" /etc/sysconfig/network-scripts/ifcfg-eth0
[root@host ~]# echo "GATEWAY=x.x.x.x" >> /etc/sysconfig/network-scripts/ifcfg-eth0
[root@host ~]# service network restart

x.x.x.x 为开启了 IP 路由转发和 NAT 的服务器的内网 IP 地址。

6 、如果其他服务器在做了上述操作以后发现外网 IP 地址可以 ping 通(如 ping 47.88.138.127 ),但是域名 ping 不通(如 ping ccie.lol ),那么请检查这台服务器上 DNS 域名解析的相关配置。

 

参考自:

  • https://blog.csdn.net/qianye_111/article/details/78987161

这篇文章对你有帮助吗?

相关文章

发表评论?

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据