如何在 Linux 和 OS X 上获取本地机器的主 IP 地址? [英] How to get the primary IP address of the local machine on Linux and OS X?
问题描述
我正在寻找一个命令行解决方案,它可以返回本地主机的主要(第一个)IP 地址,而不是 127.0.0.1
I am looking for a command line solution that would return me the primary (first) IP address of the localhost, other than 127.0.0.1
该解决方案应该至少适用于 Linux(Debian 和 RedHat)和 OS X 10.7+
The solution should work at least for Linux (Debian and RedHat) and OS X 10.7+
我知道 ifconfig
在这两个平台上都可用,但它的输出在这些平台之间不太一致.
I am aware that ifconfig
is available on both but its output is not so consistent between these platforms.
推荐答案
使用grep
从ifconfig
中过滤IP地址:
Use grep
to filter IP address from ifconfig
:
ifconfig |grep -Eo 'inet (addr:)?([0-9]*.){3}[0-9]*' |grep -Eo '([0-9]*.){3}[0-9]*' |grep -v '127.0.0.1'
或者使用sed
:
ifconfig |sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*.){3}[0-9]*).*/2/p'
如果你只对某些接口感兴趣,比如 wlan0、eth0 等,那么:
If you are only interested in certain interfaces, wlan0, eth0, etc. then:
ifconfig wlan0 |...
例如,您可以将 .bashrc
中的命令别名为创建您自己的名为 myip
的命令.
You can alias the command in your .bashrc
to create your own command called myip
for instance.
alias myip="ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*.){3}[0-9]*).*/2/p'"
更简单的方法是hostname -I
(hostname -i
用于旧版本的hostname
,但请参阅注释).但是,这仅适用于 Linux.
A much simpler way is hostname -I
(hostname -i
for older versions of hostname
but see comments). However, this is on Linux only.
这篇关于如何在 Linux 和 OS X 上获取本地机器的主 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!