我正在寻找一个命令行解决方案,将返回我的主(第一个)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,但是它的输出在这些平台之间并不一致。
当前回答
假设你需要自己的主要公共IP,就像从世界其他地方看到的那样,尝试以下任何一种:
wget http://ipecho.net/plain -O - -q
curl http://icanhazip.com
curl http://ifconfig.me/ip
其他回答
在一个默认网关的网络中查找这台计算机的IP地址(例如排除所有虚拟网络,docker桥接器)。互联网网关,wifi网关,以太网
ip route| grep $(ip route |grep default | awk '{ print $5 }') | grep -v "default" | awk '/scope/ { print $9 }'
适用于Linux。
测试:
➜ ~ ip route| grep $(ip route |grep default | awk '{ print $5 }') | grep -v "default" | awk '/scope/ { print $9 }'
192.168.0.114
➜ reverse-networking git:(feature/type-local) ✗ ifconfig wlp2s0
wlp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.0.114 netmask 255.255.255.0 broadcast 192.168.0.255
inet6 fe80::d3b9:8e6e:caee:444 prefixlen 64 scopeid 0x20<link>
ether ac:x:y:z txqueuelen 1000 (Ethernet)
RX packets 25883684 bytes 27620415278 (25.7 GiB)
RX errors 0 dropped 27 overruns 0 frame 0
TX packets 7511319 bytes 1077539831 (1.0 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
只针对Ubuntu的某些版本。尽管它可能只告诉你127.0.0.1:
hostname -i
or
hostname -I
我必须补充科林安德森的回答,这个方法也考虑到如果你有两个界面,他们都显示为向上。
ip route get 1 | awk '{print $NF;exit}'
我一直在用树莓派(Raspberry Pi)开发一个应用程序,需要实际使用的IP地址,而不仅仅是它是否启动。大多数其他答案都会返回两个IP地址,这对我的场景来说不一定有帮助。
另一个在Linux和OSX上都可以工作的ifconfig变体:
ifconfig | grep "inet " | cut -f2 -d' '
如果你已经安装了npm和node: npm install -g ip && node -e "const ip = require('ip');console.log (ip.address())”