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

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

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


当前回答

在linux系统上获取本地ipv4地址的最短方法:

hostname -I | awk '{print $1}'

其他回答

下面的代码可以在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

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

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

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

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

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

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