我正在寻找一个命令行解决方案,将返回我的主(第一个)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())”

其他回答

ip addr show | grep -E '^\s*inet' | grep -m1 global | awk '{ print $2 }' | sed 's|/.*||'

对于linux机器(不是OS X):

hostname --ip-address

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

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

不确定这是否适用于所有操作系统,尝试一下。

ifconfig | awk -F"[ :]+" '/inet addr/ && !/127.0/ {print $4}'

在Mac电脑上,考虑以下问题:

scutil --nwi | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'