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

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

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


当前回答

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

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

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

其他回答

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

linux下也可以通过该命令获取eth0的IP地址

/sbin/ip -4 -o addr show dev eth0| awk '{split($4,a,"/");print a[1]}'

输出如下所示

[root@localhost Sathish]# /sbin/ip -4 -o addr show dev eth0| awk '{split($4,a,"/");print a[1]}'
192.168.1.22

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

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机器(不是OS X):

hostname --ip-address