使用 ip route
命令(推荐)
这是最现代且准确的方法,适用于所有主流 Linux 发行版(如 Ubuntu、CentOS、Debian)。
操作步骤:
- 打开终端(快捷键
Ctrl+Alt+T
)。 - 输入命令:
ip route show default
输出示例:
default via 192.168.1.1 dev eth0 proto static metric 100
default
:表示默认路由(即网关)。via 192.168.1.1
:网关 IP 地址。dev eth0
:使用的网卡名称。
扩展用法:
- 查看所有路由表(含网关):
ip route
- 针对特定网卡(如
eth0
):ip route show dev eth0
使用 netstat
命令(传统方法)
部分旧系统可能未预装 iproute2
工具,可用 netstat
替代。
操作步骤:
netstat -rn
输出示例:
Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 eth0
- 找到
Destination
为0.0.0
的行,其Gateway
列即网关 IP(如168.1.1
)。 Iface
列显示对应的网卡(如eth0
)。
使用 route
命令(备用方案)
若系统未安装 netstat
,可使用更基础的 route
命令:
route -n
输出解读:
与 netstat -rn
类似,查找 Destination
为 0.0.0
的行,Gateway
列即网关 IP。
通过配置文件查看(静态配置时有效)
若网关为手动配置(非 DHCP 分配),可查看网络配置文件:
- Ubuntu/Debian:
cat /etc/netplan/*.yaml # 查看 Netplan 配置 cat /etc/network/interfaces # 旧版系统
- CentOS/RHEL:
cat /etc/sysconfig/network-scripts/ifcfg-eth0 # 将 eth0 替换为实际网卡名
查找
GATEWAY=
或gateway4:
字段。
使用 nmcli
(NetworkManager 用户)
若系统使用 NetworkManager 管理网络:
nmcli device show eth0 | grep 'IP4.GATEWAY' # 替换 eth0 为你的网卡
输出示例:
IP4.GATEWAY: 192.168.1.1
常见问题解答
- 为什么命令显示的网关是
0.0.0
?
表示未设置默认网关,或网卡未正确连接。 - 多网卡时如何区分网关?
使用ip route
输出中的dev ethX
可明确对应网卡。 - 网关显示为
linkdown
状态?
检查网卡物理连接或使用ip link set eth0 up
启用网卡。
总结建议
- 首选
ip route
:信息全面、准确,兼容新老系统。 - 排查步骤:
- 确认网卡已启用(
ip link show
)。 - 检查是否获取到 IP(
ip addr show eth0
)。 - 验证网关是否可达(
ping 192.168.1.1
)。
- 确认网卡已启用(
引用说明基于 Linux 内核文档(kernel.org)及主流发行版官方手册(如 Ubuntu、Red Hat),确保方法经过实践验证,命令参数参考自
man
手册(如man ip-route
)。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/7059.html