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条回答
Fickle 薄情
2楼-- · 2019-01-29 20:32

On Redhat 64bit, this solved problem for me.

ifconfig $1|sed -n 2p|awk '{ print $2 }'|awk -F : '{ print $2 }'
查看更多
疯言疯语
3楼-- · 2019-01-29 20:33

Generally, it is never guaranteed that a system will only have one IP address, for example, you can have both an ethernet and wlan connections, and if you have an active VPN connection then you'll have yet another IP address.

Linux

On Linux, hostname -I will list the current IP address(es). Relying on it always returning just one IP address will most likely not work as expected under some scenarios (i.e. a VPN link is up), so a more reliable way would be converting the result to an array and then loop over the elements:

ips=($(hostname -I))

for ip in "${ips[@]}"
do
    echo $ip
done

OSX

On OSX, if you know the interface, you could use:

~$ ipconfig getifaddr en0
192.168.1.123

which will return just the IP address.

Or you could loop over possible interface names, starting with a suffix, i.e. en:

for NUMBER in $(seq 0 5); do
    ip=`ipconfig getifaddr en$NUMBER`
    if [ -n "$ip" ]; then
        myip="$ip"
        break
    fi
done

echo $myip

Also, getting the IP address becomes non-deterministic in case both a cable and wifi connections are established, when a machine has more than one ethernet interfaces, or when VPN tunnels are present.

Getting the external IP

If you need the external IP, then you can query a text-mode service, for example curl ipecho.net/plain would return a plain text external IP.

查看更多
4楼-- · 2019-01-29 20:34

Use the following command:

/sbin/ifconfig $(netstat -nr | tail -1 | awk '{print $NF}') | awk -F: '/inet /{print $2}' | cut -f1 -d ' '
查看更多
登录 后发表回答