Which terminal command to get just IP address and nothing else?

后端 未结 29 1288
春和景丽
春和景丽 2020-12-04 06:16

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 loo

29条回答
  •  不思量自难忘°
    2020-12-04 06:35

    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'.

提交回复
热议问题