我正在寻找一个命令行解决方案,将返回我的主(第一个)IP地址的本地主机,而不是127.0.0.1

该解决方案至少适用于Linux (Debian和RedHat)和OS X 10.7+

我知道在这两个平台上都可以使用ifconfig,但是它的输出在这些平台之间并不一致。


当前回答

如果你已经安装了npm和node: npm install -g ip && node -e "const ip = require('ip');console.log (ip.address())”

其他回答

对于linux,你需要的是这个命令:

ifconfig $1|sed -n 2p|awk '{ print $2 }'|awk -F : '{ print $2 }'

在你的shell中输入这个,你就会知道你的ip。

如果你知道网络接口(eth0, wlan, tun0等):

ifconfig eth0 | grep addr: | awk '{ print $2 }' | cut -d: -f2

如果你已经安装了npm和node: npm install -g ip && node -e "const ip = require('ip');console.log (ip.address())”

适用于Mac, Linux和Docker容器内部:

$ hostname——ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;* inet (addr) ?(([0 - 9] * \){3}[0 - 9] *)。*/\2/p' | awk '{打印$1;退出}”)

也适用于Makefile:

LOCAL_HOST:= ${shell主机名——ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;* inet (addr) ?(([0 - 9] * \){3}[0 - 9] *)。*/\2/p' | awk '{打印$1;退出}”)}

我必须补充科林安德森的回答,这个方法也考虑到如果你有两个界面,他们都显示为向上。

ip route get 1 | awk '{print $NF;exit}'

我一直在用树莓派(Raspberry Pi)开发一个应用程序,需要实际使用的IP地址,而不仅仅是它是否启动。大多数其他答案都会返回两个IP地址,这对我的场景来说不一定有帮助。