伺服器無圖形介面、或需在腳本中自動取得公網 IP 時,透過外部服務回報是最直接的方法。本文彙整 curl、wget、dig、host 多種查詢方式、輸出格式(純文字/JSON/XML)、腳本整合範例。
curl -s icanhazip.com
curl -s ifconfig.me
curl -s curlmyip.com
curl -s ip.appspot.com
curl -s ipinfo.io/ip
curl -s ipecho.net/plain
curl -s www.trackip.net/i
curl -s ipinfo.io/json
curl -s ifconfig.me/all.json
curl -s www.trackip.net/ip?json
curl -s ifconfig.me/all.xml
curl -s ifconfig.me/all
# 輸出:ip_addr, ip_decimal, country, region, city, hostname, ua 等
curl -s 'https://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9.]*\).*/\1/'
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
# OpenDNS 專用解析器
dig +short myip.opendns.com @resolver1.opendns.com
# host 指令
host -t a dartsclink.com | sed 's/.*has address //'
優勢:純 DNS 流量、不被 HTTP 代理/防火牆攔截、回應極快。
#!/bin/bash
PUBLIC_IP=$(curl -s --max-time 5 icanhazip.com || wget -qO- --timeout=5 https://ipecho.net/plain)
echo "Public IP: $PUBLIC_IP"
# 記錄每日 IP 變化
echo "$(date '+%F %T') $PUBLIC_IP" >> /var/log/public-ip.log
# /etc/systemd/system/public-ip-logger.service
[Unit]
Description=Log Public IP Change
After=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/log-public-ip.sh
# /etc/systemd/system/public-ip-logger.timer
[Unit]
Description=Run IP logger every hour
[Timer]
OnCalendar=hourly
Persistent=true
[Install]
WantedBy=timers.target
| 服務 | 穩定度 | 速率限制 | 隱私 |
|---|---|---|---|
| icanhazip.com | 高 | 無公開限制 | 僅記錄 IP |
| ifconfig.me | 高 | 有限制 | 記錄 UA、Referer |
| ipinfo.io | 高 | 免費 5萬/月 | 提供地理定位 API |
| ipecho.net | 中 | 無公開限制 | 簡單純文字 |
| OpenDNS | 極高 | 無限制 | DNS 查詢日誌 |
建議:生產環境部署自建 echoip 服務(Go/Python 幾十行),或使用雲端供應商中繼資料端點(AWS https://169.254.169.254/latest/meta-data/public-ipv4、GCP https://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip、Azure https://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIp)。