如何在Linux和OS X上获取本地计算机的主IP地址? [英] How to get the primary IP address of the local machine on Linux and OS X?

查看:312
本文介绍了如何在Linux和OS X上获取本地计算机的主IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个命令行解决方案,它会返回本地主机的主(第一)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 过滤IP地址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的/ 127.0.0.1 //; s /.* inet(addr :)?(([0-9] * \。){3} [0-9] *)。* / \\\ / 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的/ 127.0.0.1 //; s /.* inet(addr :)?(([0-9] * \。){3} [0-9] *)。* / \2 / p'

更简单的方法是 hostname -I 主机名-i 旧版本主机名但请参阅注释)。但是,这仅适用于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆