我正在寻找一个命令行解决方案,将返回我的主(第一个)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,但是它的输出在这些平台之间并不一致。
当前回答
适用于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;退出}”)}
其他回答
在Mac电脑上,考虑以下问题:
scutil --nwi | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
下面的代码可以在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
如果你已经安装了npm和node: npm install -g ip && node -e "const ip = require('ip');console.log (ip.address())”
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
下面这个比较容易读: Ifconfig | grep 'inet addr:' |/usr/bin/awk '{print $2}' | tr -d addr: