如何在Linux和OS X上获取本地计算机的主IP地址? [关闭]

本文翻译自:How to get the primary IP address of the local machine on Linux and OS X? [closed]

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 我正在寻找一个命令行解决方案,该解决方案将返回本地主机的主要(第一个)IP地址,而不是127.0.0.1。

The solution should work at least for Linux (Debian and RedHat) and OS X 10.7+ 该解决方案至少应适用于Linux(Debian和RedHat)和OS X 10.7+

I am aware that ifconfig is available on both but its output is not so consistent between these platforms. 我知道ifconfig在两个平台上都可用,但是它们的输出在这些平台之间并不一致。


#1楼

参考:https://stackoom.com/question/ttmn/如何在Linux和OS-X上获取本地计算机的主IP地址-关闭


#2楼

Use grep to filter IP address from ifconfig : 使用grep过滤来自ifconfig IP地址:

ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'

Or with sed : 或使用sed

ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\\.){3}[0-9]*).*/\\2/p'

If you are only interested in certain interfaces, wlan0, eth0, etc. then: 如果仅对某些接口(wlan0,eth0等)感兴趣,则:

ifconfig wlan0 | ...

You can alias the command in your .bashrc to create your own command called myip for instance. 您可以为.bashrc的命令添加别名,以创建自己的名为myip的命令。

alias myip="ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\\.){3}[0-9]*).*/\\2/p'"

A much simpler way is hostname -I ( hostname -i for older versions of hostname but see comments). 一种更简单的方法是hostname -I (对于旧版本的hostname ,请使用hostname -i ,但请参见注释)。 However, this is on Linux only. 但是,这仅在Linux上。


#3楼

Edited ( 2014-06-01 2018-01-09) 编辑( 2014-06-01 2018-01-09)

For stronger config, with many interfaces and many IP configured on each interfaces, I wrote a pure bash script (not based on 127.0.0.1 ) for finding correct interface and ip, based on default route . 为了获得更强大的配置,并使用许多接口并在每个接口上配置了许多IP,我编写了一个纯bash脚本(不基于127.0.0.1 ),用于根据default route查找正确的接口 ip。 I post this script at very bottom of this answer. 我将此脚本发布在此答案的最底部。

Intro 介绍

As both Os have installed by default, there is a bash tip for both Mac and Linux: 由于两个输出接口上有默认安装的,没有为Mac和Linux是bash提示:

The locale issue is prevented by the use of LANG=C : 通过使用LANG=C可以防止区域设置问题:

myip=
while IFS=$': \t' read -a line ;do
    [ -z "${line%inet}" ] && ip=${line[${#line[1]}>4?1:2]} &&
        [ "${ip#127.0.0.1}" ] && myip=$ip
  done< <(LANG=C /sbin/ifconfig)
echo $myip

Putting this into a function: 将其放入函数中:

Minimal: 最小:

getMyIP() {
    local _ip _line
    while IFS=$': \t' read -a _line ;do
        [ -z "${_line%inet}" ] &&
           _ip=${_line[${#_line[1]}>4?1:2]} &&
           [ "${_ip#127.0.0.1}" ] && echo $_ip && return 0
      done< <(LANG=C /sbin/ifconfig)
}

Simple use: 使用简单:

getMyIP
192.168.1.37

Fancy tidy: 花哨的整洁:

getMyIP() {
    local _ip _myip _line _nl=$'\n'
    while IFS=$': \t' read -a _line ;do
        [ -z "${_line%inet}" ] &&
           _ip=${_line[${#_line[1]}>4?1:2]} &&
           [ "${_ip#127.0.0.1}" ] && _myip=$_ip
      done< <(LANG=C /sbin/ifconfig)
    printf ${1+-v} $1 "%s${_nl:0:$[${#1}>0?0:1]}" $_myip
}

Usage: 用法:

getMyIP
192.168.1.37

or, running same function, but with an argument: 或者,运行相同的函数,但带有一个参数:

getMyIP varHostIP
echo $varHostIP
192.168.1.37
set | grep ^varHostIP
varHostIP=192.168.1.37

Nota: Without argument, this function output on STDOUT, the IP and a newline , with an argument, nothing is printed, but a variable named as argument is created and contain IP without newline . 注意:不带参数时,此函数在STDOUT,IP和带有参数的换行符上输出,不带任何参数,但是会创建一个名为参数的变量,并且包含不带换行符的 IP。

Nota2: This was tested on Debian, LaCie hacked nas and MaxOs. 注意:已在Debian,LaCie入侵的nas和MaxOs上进行了测试。 If this won't work under your environ, I will be very interested by feed-backs! 如果在您的环境下无法解决问题,那么反馈会引起我的极大兴趣!

Older version of this answer 此答案的旧版本

( Not deleted because based on sed , not bash . ) (由于基于sed而不是bash ,因此未删除。)

Warn: There is an issue about locales! 警告:关于语言环境有问题!

Quick and small: 快速而小巧:

myIP=$(ip a s|sed -ne '/127.0.0.1/!{s/^[ \t]*inet[ \t]*\([0-9.]\+\)\/.*$/\1/p}')

Exploded (work too;) 爆炸了(也可以工作)

myIP=$(
    ip a s |
    sed -ne '
        /127.0.0.1/!{
            s/^[ \t]*inet[ \t]*\([0-9.]\+\)\/.*$/\1/p
        }
    '
)

Edit: 编辑:

How! 怎么样! This seem not work on Mac OS ... 这似乎不适用于Mac OS ...

Ok, this seem work quite same on Mac OS as on my Linux : 好的,这在Mac OSLinux上似乎完全相同:

myIP=$(LANG=C /sbin/ifconfig  | sed -ne $'/127.0.0.1/ ! { s/^[ \t]*inet[ \t]\\{1,99\\}\\(addr:\\)\\{0,1\\}\\([0-9.]*\\)[ \t\/].*$/\\2/p; }')

splitted: 分裂:

myIP=$(
    LANG=C /sbin/ifconfig  |
        sed -ne $'/127.0.0.1/ ! {
            s/^[ \t]*inet[ \t]\\{1,99\\}\\(addr:\\)\\{0,1\\}\\([0-9.]*\\)[ \t\/].*$/\\2/p;
        }')

My script (jan 2018): 我的脚本(2018年1月):

This script will first find your default route and interface used for, then search for local ip matching network of gateway and populate variables. 该脚本将首先找到用于的默认路由接口 ,然后搜索网关的本地ip匹配网络并填充变量。 The last two lines just print, something like: 最后两行只是打印,类似于:

Interface   : en0
Local Ip    : 10.2.5.3
Gateway     : 10.2.4.204
Net mask    : 255.255.252.0
Run on mac  : true

or 要么

Interface   : eth2
Local Ip    : 192.168.1.31
Gateway     : 192.168.1.1
Net mask    : 255.255.255.0
Run on mac  : false

Well, there it is: 好吧,它是:

#!/bin/bash
runOnMac=false
int2ip() { printf ${2+-v} $2 "%d.%d.%d.%d" \
        $(($1>>24)) $(($1>>16&255)) $(($1>>8&255)) $(($1&255)) ;}
ip2int() { local _a=(${1//./ }) ; printf ${2+-v} $2 "%u" $(( _a<<24 |
                  ${_a[1]} << 16 | ${_a[2]} << 8 | ${_a[3]} )) ;}
while IFS=$' :\t\r\n' read a b c d; do
    [ "$a" = "usage" ] && [ "$b" = "route" ] && runOnMac=true
    if $runOnMac ;then
        case $a in 
            gateway )    gWay=$b  ;;
            interface )  iFace=$b ;;
        esac
    else
        [ "$a" = "0.0.0.0" ] && [ "$c" = "$a" ] && iFace=${d##* } gWay=$b
    fi
done < <(/sbin/route -n 2>&1 || /sbin/route -n get 0.0.0.0/0)
ip2int $gWay gw
while read lhs rhs; do
    [ "$lhs" ] && { 
        [ -z "${lhs#*:}" ] && iface=${lhs%:}
        [ "$lhs" = "inet" ] && [ "$iface" = "$iFace" ] && {
            mask=${rhs#*netmask }
            mask=${mask%% *}
            [ "$mask" ] && [ -z "${mask%0x*}" ] &&
                printf -v mask %u $mask ||
                ip2int $mask mask
            ip2int ${rhs%% *} ip
            (( ( ip & mask ) == ( gw & mask ) )) &&
                int2ip $ip myIp && int2ip $mask netMask
        }
    }
done < <(/sbin/ifconfig)
printf "%-12s: %s\n" Interface $iFace Local\ Ip $myIp \
       Gateway $gWay Net\ mask $netMask Run\ on\ mac $runOnMac

#4楼

不知道这是否适用于所有操作系统,请尝试一下。

ifconfig | awk -F"[ :]+" '/inet addr/ && !/127.0/ {print $4}'

#5楼

对于linux机器(不是OS X):

hostname --ip-address

#6楼

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章