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

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

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


当前回答

主网口IP

ifconfig `ip route | grep default | head -1 | sed 's/\(.*dev \)\([a-z0-9]*\)\(.*\)/\2/g'` | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | head -1

其他回答

ifconfig | grep "inet addr:" | grep -v "127.0.0.1" | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'  | head -1

我提取我对这个答案的评论:

ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'

它基于@CollinAnderson的答案,但对我来说没用。

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

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

hostname --ip-address

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

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