伺服器往往位於 NAT 之後,ifconfig/ip a 僅見私網 IP。本文匯總 15+ 種終端查詢公網 IP 方法,涵蓋純文本/JSON/XML 格式、多服務商冗餘、DNS 反查、腳本化整合。
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
# JSON
curl ipinfo.io/json
curl ifconfig.me/all.json
# XML
curl ifconfig.me/all.xml
# 完整資訊 (IP、UA、端口、地理位置等)
curl ifconfig.me/all
# sed 擷取
curl -s 'https://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9.]*\).*/\1/'
# grep 擷取
curl -s https://checkip.dyndns.org/ | grep -o '[0-9.]\+'
wget https://ipecho.net/plain -O - -q; echo
wget https://observebox.com/ip -O - -q; echo
# host
host -t a dartsclink.com | sed 's/.*has address //'
# dig (OpenDNS 解析器)
dig +short myip.opendns.com @resolver1.opendns.com
#!/bin/bash
# 多源冗餘查詢,首個成功即返回
get_public_ip() {
local services=(
"curl -s --max-time 5 icanhazip.com"
"curl -s --max-time 5 ifconfig.me"
"curl -s --max-time 5 ipinfo.io/ip"
"wget -q -O - --timeout=5 https://ipecho.net/plain"
"dig +short +time=5 myip.opendns.com @resolver1.opendns.com"
)
for cmd in "${services[@]}"; do
ip=$(eval "$cmd" 2>/dev/null | tr -d '\r\n' | grep -Eo '^[0-9]{1,3}(\.[0-9]{1,3}){3}$')
[[ -n "$ip" ]] && { echo "$ip"; return 0; }
done
echo "FAILED" >&2
return 1
}
PUBLIC_IP=$(get_public_ip)
echo "Public IP: $PUBLIC_IP"
| 服務 | 格式 | 穩定性 | 頻率限制 | 備註 |
|---|---|---|---|---|
| icanhazip.com | text | 高 | 低 | 極簡 |
| ipinfo.io | text/json | 高 | 免費 5萬/天 | 含地理位置 |
| ifconfig.me | text/json/xml/all | 中 | 有 | 功能最全 |
| OpenDNS dig | text | 極高 | 無 | 企業級解析器 |