请给出Linux中eth0的IP地址和广播地址的指令?

参考回答

在 Linux 中,可以使用 ipifconfig 命令来查看 eth0IP 地址广播地址

1. 使用 ip 命令(推荐)

ip -4 addr show eth0
Bash

或更精确地提取:

ip -4 addr show eth0 | grep inet | awk '{print "IP地址:", 2, "广播地址:",4}'
Bash

2. 使用 ifconfig(较旧但仍常见)

ifconfig eth0
Bash

或提取具体信息:

ifconfig eth0 | grep 'inet ' | awk '{print "IP地址:", 2, "广播地址:",6}'
Bash

详细讲解与拓展

1. ip 命令的输出解析

ip addr show eth0 可能返回:

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    inet 192.168.1.100/24 brd 192.168.1.255 scope global dynamic eth0
       valid_lft 86347sec preferred_lft 86347sec

其中:
inet 192.168.1.100/24192.168.1.100IP 地址
brd 192.168.1.255192.168.1.255广播地址

2. ifconfig 命令解析

ifconfig eth0 可能返回:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
        inet 192.168.1.100 netmask 255.255.255.0 broadcast 192.168.1.255
  • inet 192.168.1.100192.168.1.100IP 地址
  • broadcast 192.168.1.255192.168.1.255广播地址

3. hostname -I 另一种获取 IP

如果只想获取当前设备的 IP,可以使用:

hostname -I
Bash

但它不会显示广播地址。

4. nmcli(适用于 NetworkManager)

NetworkManager 运行的系统(如 Ubuntu、CentOS 7+)上,可以使用:

nmcli device show eth0 | grep -E 'IP4.ADDRESS|IP4.BROADCAST'
Bash

总结

  • 推荐使用 ip 命令ip -4 addr show eth0,速度快,现代 Linux 发行版的标准工具。
  • 如果 ifconfig 可用,可以用 ifconfig eth0(但 ifconfig 已被淘汰)。
  • 只要 IP,不关心广播地址,可以用 hostname -I
  • 适用于 NetworkManager 的命令nmcli device show eth0

使用 ip 命令是当前最佳实践,掌握它能更高效地管理 Linux 网络接口。

发表评论

后才能评论