如何显示接口的IP地址?

use*_*556 18 networking shell bash ip ip-address

如果我想显示分配给 eth1 的 IP 地址,我该如何在 Bash 中执行此操作?

use*_*517 14

试试这个 (Linux)

/sbin/ifconfig eth1 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1
Run Code Online (Sandbox Code Playgroud)

或者这个(Linux)

/sbin/ifconfig eth0 | awk -F ' *|:' '/inet addr/{print $4}'
Run Code Online (Sandbox Code Playgroud)

或者这个 (*BSD)

ifconfig bge0 | grep 'inet' | cut -d' ' -f2
Run Code Online (Sandbox Code Playgroud)

或者这个(Solaris 10)

ifconfig e1000g0 | awk '/inet / {print $6}'
Run Code Online (Sandbox Code Playgroud)

显然,更改接口名称以匹配您想要从中获取信息的名称。

  • 也工作 ifconfig eth1| awk -F ' *|:' '/inet addr/{print $4}' (2认同)

Jas*_* H. 10

在 Linux 系统上:

hostname --all-ip-addresses
Run Code Online (Sandbox Code Playgroud)

只会给你IP地址。

在 Solaris 系统上使用:

ifconfig e1000g0 | awk '/inet / {print $2}'
Run Code Online (Sandbox Code Playgroud)

  • 从主机名(1)手册页:“避免使用此选项;使用主机名 --all-ip-addresses 代替。 (2认同)

小智 10

要获取带有网络掩码的 IPv4 和 IPv6 IP 地址,只需尝试:

ip a l eth1 | awk '/inet/ {print $2}'
Run Code Online (Sandbox Code Playgroud)

或者没有网络掩码(无法想象为什么你需要一个没有掩码的IP地址):

ip a l eth1 | awk '/inet/ {print $2}' | cut -d/ -f1
Run Code Online (Sandbox Code Playgroud)

  • “无法想象为什么你需要一个没有掩码的 IP 地址” 很简单,支持它的客户端很少。您无法 ping 通 1.1.1.1/32。https://1.1.1.1/32 将返回 404。您不能将 A 记录指向它,也不能将其插入到反向代理配置中,也不能通过隧道连接到它,也不能将其放入 /etc/hosts 中。 (3认同)

小智 9

更好的方法:从命令“ip”获取 ip 地址,因为“ifconfig”已过时。否则你会在使用“ifconfig”时遇到问题,因为 ifconfig 的输出是语言相关的。

我使用此命令获取所有 IP (IPv4):

ip addr show | grep -o "inet [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" | grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"
Run Code Online (Sandbox Code Playgroud)


pst*_*ton 7

正如@Manuel 所提到的,ifconfig已过时,并且ip是未来推荐的方法。

ip -f inet addr show eth1

并使用@bleater 的 sed 或 @Jason H. 的 awk 来过滤输出(取决于您是否需要掩码)

ip -f inet addr show eth1 | sed -En -e 's/.*inet ([0-9.]+).*/\1/p'

ip -f inet addr show eth1 | awk '/inet / {print $2}'


小智 5

在各种 Linux 上运行良好:

ip -brief address show eth0 | awk '{print $3}' | awk -F/ '{print $1}'
Run Code Online (Sandbox Code Playgroud)