在 CentOS 系统中,使用 ifconfig
命令直接设置网关并不是一个推荐的做法,因为 ifconfig
主要用于配置网络接口的 IP 地址、子网掩码等信息。设置默认网关通常使用 route
或 ip route
命令。
以下是使用 route
和 ip route
命令设置默认网关的方法:
route
命令查看当前路由表:
route -n
添加默认网关:
sudo route add default gw <gateway_ip> <interface>
例如,如果你的默认网关是 192.168.1.1
,接口是 eth0
,则命令为:
sudo route add default gw 192.168.1.1 eth0
永久保存路由设置:
编辑 /etc/sysconfig/network-scripts/route-eth0
文件(假设你的接口是 eth0
),添加以下内容:
ADDRESS0=192.168.1.100
NETMASK0=255.255.255.0
GATEWAY0=192.168.1.1
重启网络服务:
sudo systemctl restart network
ip route
命令查看当前路由表:
ip route show
添加默认网关:
sudo ip route add default via <gateway_ip> dev <interface>
例如,如果你的默认网关是 192.168.1.1
,接口是 eth0
,则命令为:
sudo ip route add default via 192.168.1.1 dev eth0
永久保存路由设置:
编辑 /etc/sysconfig/network-scripts/route-eth0
文件(假设你的接口是 eth0
),添加以下内容:
ADDRESS0=192.168.1.100
NETMASK0=255.255.255.0
GATEWAY0=192.168.1.1
重启网络服务:
sudo systemctl restart network
nmcli
或 nmtui
工具来管理网络配置。sudo nmcli connection modify <connection_name> ipv4.gateway <gateway_ip>
sudo nmcli connection up <connection_name>
其中 <connection_name>
是你的网络连接名称。通过以上方法,你可以成功地在 CentOS 系统中设置默认网关。