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