Which terminal command to get just IP address and

2019-01-29 19:33发布

I'm trying to use just the IP address (inet) as a parameter in a script I wrote.

Is there an easy way in a unix terminal to get just the IP address, rather than looking through ifconfig?

21条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-29 20:24

To get only the IP address on Mac OS X you can type the following command:

ipconfig getifaddr en0
查看更多
Anthone
3楼-- · 2019-01-29 20:28

If you have limited environment, you may use this command:

ip -4 addr show dev eth0 | grep inet | tr -s " " | cut -d" " -f3 | head -n 1
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-29 20:28

You can also use the following command:

ip route | grep src

NOTE: This will only work if you have connectivity to the internet.

查看更多
我只想做你的唯一
5楼-- · 2019-01-29 20:29

Here is my version, in which you can pass a list of interfaces, ordered by priority:

getIpFromInterface()
{
    interface=$1
    ifconfig ${interface}  > /dev/null 2>&1 && ifconfig ${interface} | awk -F'inet ' '{ print $2 }' | awk '{ print $1 }' | grep .
}

getCurrentIpAddress(){
    IFLIST=(${@:-${IFLIST[@]}})
    for currentInterface in ${IFLIST[@]}
    do
        IP=$(getIpFromInterface  $currentInterface)
        [[ -z "$IP" ]] && continue
    echo ${IP/*:}
    return
    done
}

IFLIST=(tap0 en1 en0)
getCurrentIpAddress $@

So if I'm connected with VPN, Wifi and ethernet, my VPN address (on interface tap0) will be returned. The script works on both linux and osx, and can take arguments if you want to override IFLIST

Note that if you want to use IPV6, you'll have to replace 'inet ' by 'inet6'.

查看更多
smile是对你的礼貌
6楼-- · 2019-01-29 20:30
hostname -I  

This command will give you the exact ip address as you want in Ubuntu.

查看更多
在下西门庆
7楼-- · 2019-01-29 20:30
curl ifconfig.co 

This returns only the ip address of your system.

查看更多
登录 后发表回答