萬盛學電腦網

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

Linux 獲取公網 IP 地址的多種方法:curl、wget、DNS 查詢與腳本整合

前言:為什麼需要程式化獲取公網 IP?

在雲端伺服器、容器、VPN、NAT 環境中,ifconfig/ip addr 僅顯示私有 IP (如 10.x, 172.16.x, 192.168.x)。自動化腳本 (DDNS 更新、防火牆規則同步、監控告警、CI/CD 部署) 需要可靠獲取公網出口 IP。本文整理多種方法、可靠性比較、失效備援策略與整合範例。

方法一:HTTP API 服務 (最常用、最簡單)

服務指令回應格式支援協議限制/備註
ipinfo.iocurl -s https://ipinfo.io/ip純文字 IPHTTPS免費額度豐富、支援 JSON 完整資訊
ifconfig.mecurl -s https://ifconfig.me純文字 IPHTTPS簡單穩定
icanhazip.comcurl -s https://icanhazip.com純文字 IP (+換行)HTTPS極簡
ident.mecurl -s https://ident.me純文字 IPHTTPS-
api.ipify.orgcurl -s https://api.ipify.org純文字 IPHTTPS可加 ?format=json
checkip.amazonaws.comcurl -s https://checkip.amazonaws.com純文字 IP (+換行)HTTPSAWS 官方、高可用
members.3322.orgcurl -s https://members.3322.org/dyndns/getip純文字 IPHTTP國內舊服務、不支援 HTTPS
ip.sbcurl -s https://ip.sbJSON/純文字HTTPS支援國內線路優化
myip.ipip.netcurl -s https://myip.ipip.net文字含地理位置HTTPS中文友善

最佳實踐:多服務輪詢備援

#!/bin/bash
# get_public_ip.sh - 可靠獲取公網 IP,支援多源備援

SERVICES=(
  "https://api.ipify.org"
  "https://ifconfig.me"
  "https://icanhazip.com"
  "https://checkip.amazonaws.com"
  "https://ipinfo.io/ip"
)

get_ip() {
  for url in "${SERVICES[@]}"; do
    ip=$(curl -s --max-time 5 --connect-timeout 3 "$url" | tr -d '[:space:]')
    if [[ $ip =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then
      echo "$ip"
      return 0
    fi
  done
  return 1
}

IP=$(get_ip)
if [ $? -eq 0 ]; then
  echo "公網 IP: $IP"
  # 後續邏輯:更新 DDNS、發送告警、寫入配置...
else
  echo "錯誤: 無法獲取公網 IP" >&2
  exit 1
fi

方法二:DNS 查詢 (更快、無 HTTP 開銷、適合高頻)

OpenDNS / Google DNS 提供特殊查詢域名回傳查詢者公網 IP。

# OpenDNS (推薦,支援 IPv4/IPv6)
dig +short myip.opendns.com @resolver1.opendns.com
# 或
dig +short myip.opendns.com @208.67.222.222

# Google DNS
dig +short o-o.myaddr.l.google.com @ns1.google.com
# 或
dig +short o-o.myaddr.l.google.com @8.8.8.8

# 使用 nslookup (較通用)
nslookup myip.opendns.com resolver1.opendns.com | awk '/^Address: / {print $2}'
DNS 查詢通常 < 50ms,比 HTTP API 快 5-10 倍,適合高頻輪詢 (如每分鐘檢查 IP 變動)。

方法三:本地介面 + 路由推導 (無外部依賴)

若機器直接掛載公網 IP (無 NAT),可直接讀取介面:

# 取得預設路由介面
IFACE=$(ip route show default | awk '/default/ {print $5}')
# 取得該介面 IPv4
ip -4 addr show dev "$IFACE" | awk '/inet / {print $2}' | cut -d/ -f1

若在 NAT 後方,此法無法取得公網 IP,需結合 STUN 或上述 HTTP/DNS 方法。

方法四:STUN 協議 (NAT 穿透標準)

# 使用 stunclient (需安裝 stun-client)
stunclient stun.l.google.com 19302 2>&1 | grep "Mapped address" | awk '{print $4}'

# 或使用 netcat 手工 (學習用)
echo -en '\x00\x01\x00\x00\x21\x12\xa4\x42\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' | nc -u -w 2 stun.l.google.com 19302 | od -x

方法五:路由器/防火牆 API (企業級)

若控制網關設備 (OpenWrt、pfSense、MikroTik、FortiGate、Cisco ASA),直接查詢設備 WAN 介面 IP 最準確:

# OpenWrt UCI
uci get network.wan.ipaddr

# MikroTik RouterOS API
/ip address get [find interface=wan] value=address

# pfSense (需 REST API 權限)
curl -k -u "api_key" "https://pfsense/api/v1/interface/wan"

整合應用場景

1. DDNS 自動更新 (Cloudflare 範例)

#!/bin/bash
# cloudflare_ddns.sh
ZONE="example.com"
RECORD="home"
TOKEN="your_api_token"
TTL=300

IP=$(get_ip) || exit 1
RECORD_ID=$(curl -s -H "Authorization: Bearer $TOKEN" \
  "https://api.cloudflare.com/client/v4/zones?name=$ZONE" | jq -r '.result[0].id')
# 完整腳本略... (查詢現有記錄 IP,異則 PATCH 更新)

2. 伺服器啟動通知 (Telegram/Slack/Email)

IP=$(get_ip)
curl -s -X POST "https://api.telegram.org/bot/sendMessage" \
  -d chat_id= \
  -d text="🟢 Server started. Public IP: $IP"

3. 防火牆動態白名單 (iptables/nftables)

# 允許當前公網 IP 存取管理埠 (22/443/8080)
CURRENT_IP=$(get_ip)
iptables -I INPUT -s "$CURRENT_IP" -p tcp -m multiport --dports 22,443,8080 -j ACCEPT
# 配合 cron 定期更新

IPv6 獲取

# HTTP API
curl -s https://api6.ipify.org
curl -s https://ifconfig.me/ip

# DNS
dig +short myip.opendns.com @resolver1.ipv6.opendns.com AAAA

效能與可靠性比較

方法延遲可靠性適用場景
HTTP API (HTTPS)100-500ms高 (多源備援)通用、腳本整合、低頻
DNS 查詢20-80ms極高 (DNS 基礎設施)高頻輪詢、嵌入式裝置
本地介面<1ms僅直連公網有效無 NAT 環境、容器 Host Network
STUN50-200ms中 (依賴 STUN 伺服器)NAT 類型偵測、P2P 連線
路由器 API10-100ms最高 (權威來源)企業網關、SD-WAN、家庭實驗室

安全性提醒

  • 公開 IP 屬於敏感資訊,勿記錄至公開日誌、前端頁面、Git 提交。
  • API 金鑰 (Cloudflare Token 等) 必須最小權限、定期輪換、存放於密碼管理器/Secret Manager。
  • 生產環境建議架設自有 IP 回顯服務 (簡單 Nginx return 200 $remote_addr;),消除第三方依賴。

延伸閱讀

獲取公網 IP 看似簡單,但生產環境需考量可用性 (多源備援)、延遲 (DNS vs HTTP)、安全性 (最小權限、自有服務)。建立標準化 get_public_ip() 函式庫並納入基礎設施代碼庫,讓所有自動化腳本複用同一可靠實作,是成熟運維體系的標誌。

copyright © 萬盛學電腦網 all rights reserved