無圖形界面的服務器、極簡容器、自動化腳本中,快速獲取本機公網 IP 是常見需求。本文匯總 curl、wget、host、dig 等工具調用公共 IP 服務接口的多種方式,涵盖純文本、JSON、XML 格式,並提供可直接嵌入腳本的變量賦值示例。
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
均直接輸出類似 203.0.113.45 的純 IP 地址,適合管道處理。
curl ipinfo.io/json
curl ifconfig.me/all.json
curl www.trackip.net/ip?json
curl ifconfig.me/all.xml
curl ifconfig.me/all
curl -s 'https://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\1/g'
curl -s https://checkip.dyndns.org/ | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'
wget -qO- https://ipecho.net/plain; echo
wget -qO- https://observebox.com/ip; echo
-qO- 靜默輸出到 stdout,echo 換行美化。
host -t a dartsclink.com | sed 's/.*has address //'
dig +short myip.opendns.com @resolver1.opendns.com
利用 OpenDNS 解析器返回查詢者 IP,穩定性極高。
#!/bin/bash
PUBLIC_IP=$(wget -qO- https://ipecho.net/plain)
echo "Current Public IP: $PUBLIC_IP"
# 或帶超時與重試
PUBLIC_IP=$(curl -s --max-time 5 --retry 2 icanhazip.com)
| 服務 | 穩定性 | 速度 | 備註 |
|---|---|---|---|
| icanhazip.com | ★★★★★ | 快 | 純文本,極簡 |
| ifconfig.me | ★★★★☆ | 中 | 支持多格式 |
| ipinfo.io | ★★★★☆ | 中 | 含地理信息 |
| OpenDNS dig | ★★★★★ | 快 | DNS 層面,無 HTTP 依賴 |
curl -s icanhazip.com 或 dig +short myip.opendns.com @resolver1.opendns.com--max-time 與 --retry 防止掛起。