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

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

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


当前回答

假设你需要自己的主要公共IP,就像从世界其他地方看到的那样,尝试以下任何一种:

wget http://ipecho.net/plain -O - -q
curl http://icanhazip.com
curl http://ifconfig.me/ip

其他回答

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

hostname --ip-address

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

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

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

使用grep从ifconfig中过滤IP地址:

ifconfig | grep eo的inet (addr:) ?([0 - 9] * \){3}[0 - 9] *’| grep eo”([0 - 9]* \){3}[0 - 9]*’| grep - v 127.0.0.1的

或者用sed:

ifconfig | sed -En 's/127.0.0.1//;* inet (addr) ?(([0 - 9] * \){3}[0 - 9] *)。* / \ 2 / p”

如果你只对某些接口感兴趣,比如wlan0、eth0等,那么:

ifconfig wlan0 | ...

例如,您可以在.bashrc中使用别名来创建自己的命令myip。

别名myip =“ifconfig | sed -En’s / 127 . 0 0。1;s /。* inet(键入https://www.bittrex.com:) ?(0 - 9) *[\。)0 - 9]{3}[*)* \ 2 / p’”。

一个更简单的方法是hostname -I (hostname -I用于旧版本的hostname,但请参阅注释)。但是,这仅适用于Linux。

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

另一个在Linux和OSX上都可以工作的ifconfig变体:

ifconfig | grep "inet " | cut -f2 -d' '