我正在寻找一个命令行解决方案,将返回我的主(第一个)IP地址的本地主机,而不是127.0.0.1
该解决方案至少适用于Linux (Debian和RedHat)和OS X 10.7+
我知道在这两个平台上都可以使用ifconfig,但是它的输出在这些平台之间并不一致。
我正在寻找一个命令行解决方案,将返回我的主(第一个)IP地址的本地主机,而不是127.0.0.1
该解决方案至少适用于Linux (Debian和RedHat)和OS X 10.7+
我知道在这两个平台上都可以使用ifconfig,但是它的输出在这些平台之间并不一致。
当前回答
如果你知道网络接口(eth0, wlan, tun0等):
ifconfig eth0 | grep addr: | awk '{ print $2 }' | cut -d: -f2
其他回答
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
这适用于Linux和OSX
这将获得与默认路由关联的接口
NET_IF=`netstat -rn | awk '/^0.0.0.0/ {thif=substr($0,74,10); print thif;} /^default.*UG/ {thif=substr($0,65,10); print thif;}'`
使用上面发现的接口,获取ip地址。
NET_IP=`ifconfig ${NET_IF} | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'`
OSX
uname -a
达尔文笔记本14.4.0达尔文内核版本14.4.0:Thu 5月28日11:35:04 PDT 2015;根:xnu-2782.30.5 ~ 1 / RELEASE_X86_64 x86_64
echo $NET_IF
en5
echo $NET_IP
192.168.0.130
Linux CentOS
uname -a
Linux dev-cil.medfx。当地2.6.18-164。el5xen 1 SMP Thu Sep 3 04:03:03 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
echo $NET_IF
eth0
echo $NET_IP
192.168.46.10
对于linux机器(不是OS X):
hostname --ip-address
只针对Ubuntu的某些版本。尽管它可能只告诉你127.0.0.1:
hostname -i
or
hostname -I
适用于Mac, Linux和Docker容器内部:
$ hostname——ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;* inet (addr) ?(([0 - 9] * \){3}[0 - 9] *)。*/\2/p' | awk '{打印$1;退出}”)
也适用于Makefile:
LOCAL_HOST:= ${shell主机名——ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;* inet (addr) ?(([0 - 9] * \){3}[0 - 9] *)。*/\2/p' | awk '{打印$1;退出}”)}