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

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

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


当前回答

ifconfig $(netstat -rn | grep -E "^default|^0.0.0.0" | head -1 | awk '{print $NF}') | grep 'inet ' | awk '{print $2}' | grep -Eo '([0-9]*\.){3}[0-9]*' 

其他回答

在Linux上

hostname -I

在macOS

ipconfig getifaddr en0

hostname -I可以以不可靠的顺序返回多个地址(请参阅hostname manpage),但对我来说,它只返回192.168.1。X,也就是你想要的。

下面的代码可以在Linux上运行,但不能在OSX上运行。

这根本不依赖于DNS,即使/etc/hosts没有正确设置(1是1.0.0.0的简写),它也能工作:

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

或者避免awk,使用谷歌的公共DNS 8.8.8.8。

ip route get 8.8.8.8 | head -1 | cut -d' ' -f8

一种不太可靠的方式:(见下面的评论)

hostname -I | cut -d' ' -f1

使用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。

下面这个比较容易读: Ifconfig | grep 'inet addr:' |/usr/bin/awk '{print $2}' | tr -d addr:

ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}'