我正在尝试将我的互联网 IP 地址保存到 shell 中的变量中。
我试过了
ip=`host 'localhost' | awk '{print $4}'`
但这会返回
127.0.0.1
如何将互联网 IP 地址保存到 shell 中的变量中?
最佳答案
要获取所有本地接口(interface)的 IP 地址,请尝试使用 ifconfig
,例如如下所示:
$ ifconfig | awk '/inet / { print $2 }'
127.0.0.1
10.8.0.34
192.168.1.2
在这里你可以看到我有 3 个地址(环回适配器、以太网和 wifi)。如果您知道您的本地网络地址采用 192.*
形式,则可以通过以下方式仅获取该地址:
$ ifconfig | awk '/inet *192/ { print $2 }'
192.168.1.2
并将其存储到变量中:
ip=$(ifconfig | awk '/inet *192/ { print $2 }')
或者,将所有地址存储在 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
要获取 IPv6 地址,请查找 inet6
而不是 inet
。
关于linux - 在 shell 中确定互联网 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101155/