温馨提示×

linux ifconfig如何设置网关

小樊
38
2026-10-29 07:08:28
栏目: 智能运维

在 Linux 中,ifconfig 本身不能直接设置网关。ifconfig 只负责配置网络接口(IP 地址、子网掩码等),网关需要通过 route 或 ip 命令来设置。

下面按常见情况说明:


一、使用 ifconfig + route 设置(传统方式)

1. 先用 ifconfig 配置 IP

ifconfig eth0 192.168.1.100 netmask 255.255.255.0 up

2. 再用 route 设置网关

route add default gw 192.168.1.1

查看网关:

route -n

删除网关(如需):

route del default gw 192.168.1.1

二、使用 ip 命令(推荐,现代方式)

ifconfig 已逐渐被 ip 取代。

ip addr add 192.168.1.100/24 dev eth0
ip link set eth0 up
ip route add default via 192.168.1.1

查看:

ip route

三、临时 vs 永久

以上方法 重启后失效。

永久生效(以 CentOS / RHEL 为例)

编辑:

/etc/sysconfig/network-scripts/ifcfg-eth0

示例:

DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1

Ubuntu(旧版)

编辑:

/etc/network/interfaces
auto eth0
iface eth0 inet static
    address 192.168.1.100
    netmask 255.255.255.0
    gateway 192.168.1.1

Ubuntu(Netplan,新版)

network:
  version: 2
  ethernets:
    eth0:
      addresses: [192.168.1.100/24]
      gateway4: 192.168.1.1

总结

  • ✅ ifconfig:只能设 IP
  • ✅ 设网关用:route / ip route
  • ✅ 永久配置要改网卡配置文件

如果你告诉我 Linux 发行版 + 版本,我可以给你最准确的方法。

0 踩