萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 終端機查詢公網 IP 多種方法:curl、wget、dig、host 實測

伺服器無圖形介面、或需在腳本中自動取得公網 IP 時,透過外部服務回報是最直接的方法。本文彙整 curl、wget、dig、host 多種查詢方式、輸出格式(純文字/JSON/XML)、腳本整合範例。

一、curl 方案(推薦,支援豐富格式)

純文字輸出(最適合腳本)


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

JSON 格式(含地理位置、ISP 等)


curl -s ipinfo.io/json
curl -s ifconfig.me/all.json
curl -s www.trackip.net/ip?json

XML 格式


curl -s ifconfig.me/all.xml

完整資訊(ifconfig.me)


curl -s ifconfig.me/all
# 輸出:ip_addr, ip_decimal, country, region, city, hostname, ua 等

DynDNS 相容端點


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 方案(無 curl 環境備用)


wget -qO- https://ipecho.net/plain; echo
wget -qO- https://observebox.com/ip; echo

三、DNS 方案(dig/host,無需 HTTP 服務)


# OpenDNS 專用解析器
dig +short myip.opendns.com @resolver1.opendns.com

# host 指令
host -t a dartsclink.com | sed 's/.*has address //'

優勢:純 DNS 流量、不被 HTTP 代理/防火牆攔截、回應極快。

四、腳本整合範例

Bash 變數捕獲


#!/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)。

copyright © 萬盛學電腦網 all rights reserved