Linux系统获取公网IP地址的多种命令行方案
在Linux操作系统中,有多种便捷的方式可以查询当前连接的外网IP地址。以下是对这些常用方法的详细总结与整理。
首先介绍使用Curl命令以纯文本格式输出IP信息的方法。
curl icanhazip.com
curl ifconfig.me
curl curlmyip.com
curl ip.appspot.com
curl ipinfo.io/ip
curl ipecho.net/plain
curl www.trackip.net/i
接着展示如何利用Curl命令获取JSON格式的输出结果,便于程序解析。
curl ipinfo.io/json
curl ifconfig.me/all.json
curl www.trackip.net/ip?json (有点丑陋)
此外,还可以使用Curl命令请求并获取XML格式的数据响应。
curl ifconfig.me/all.xml
如果需要获取更详细的IP相关信息,可以使用Curl命令进行深度挖掘。
curl ifconfig.me/all
对于使用了DYDNS服务的用户,可以采用特定的方法来查询IP。
curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\1/g'
curl -s http://checkip.dyndns.org/ | grep -o "[[:digit:].]\+"
除了Curl,还可以使用Wget命令来替代实现相同的功能。
wget http://ipecho.net/plain -O - -q ; echo
wget http://observebox.com/ip -O - -q ; echo
另外,系统中自带的host和dig命令也是查询IP的有效工具。
如果环境中安装了这些工具,可以直接调用它们来获取所需信息。
host -t a dartsclink.com | sed 's/.*has address //'
dig +short myip.opendns.com @resolver1.opendns.com
下面提供一个简单的Bash脚本示例,展示如何自动化执行IP查询。
#!/bin/bash
PUBLIC_IP=`wget http://ipecho.net/plain -O - -q ; echo`
echo $PUBLIC_IP
希望以上内容能对各位有所帮助,感谢大家对本站的支持!