简体   繁体   English

确定外壳中的Internet IP地址?

[英]Determine internet IP address in shell?

I'm trying to save my internet IP address to a variable in the shell. 我正在尝试将我的Internet IP地址保存到外壳中的变量中。

I tried 我试过了

ip=`host 'localhost' | awk '{print $4}'`

But that returns 但这又回来了

127.0.0.1

How to save internet IP address to a variable in the shell? 如何将Internet IP地址保存到Shell中的变量?

To get IP addresses of all you local interfaces, try using ifconfig , for example like this: 要获取所有本地接口的IP地址,请尝试使用ifconfig ,例如:

$ ifconfig | awk '/inet / { print $2 }'
127.0.0.1
10.8.0.34
192.168.1.2

Here you can see I have 3 addresses (the loopback adapter, ethernet and wifi). 在这里您可以看到我有3个地址(回送适配器,以太网和wifi)。 If you know your local network address has 192.* form, you can get only that one with: 如果您知道本地网络地址具有192.*表格,则只能通过以下方式获得该地址:

$ ifconfig | awk '/inet *192/ { print $2 }'
192.168.1.2

And to store it into a variable: 并将其存储到变量中:

ip=$(ifconfig | awk '/inet *192/ { print $2 }')

Or, to store all addresses in a bash array: 或者,将所有地址存储在bash数组中:

$ ips=($(ifconfig | awk '/inet / { print $2 }'))
$ printf "ip: %s\n" "${ips[@]}"
ip: 127.0.0.1
ip: 10.8.0.34
ip: 192.168.1.2

To get IPv6 addresses, look for inet6 instead of inet . 要获取IPv6地址,请查找inet6而不是inet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM