萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 終端查詢公網 IP 完整工具箱:curl、wget、dig、host、腳本化範例

伺服器往往位於 NAT 之後,ifconfig/ip a 僅見私網 IP。本文匯總 15+ 種終端查詢公網 IP 方法,涵蓋純文本/JSON/XML 格式、多服務商冗餘、DNS 反查、腳本化整合。

1. curl 純文本輸出 (最常用)

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

2. curl 結構化輸出 (適合程式解析)

# JSON
curl ipinfo.io/json
curl ifconfig.me/all.json

# XML
curl ifconfig.me/all.xml

# 完整資訊 (IP、UA、端口、地理位置等)
curl ifconfig.me/all

3. DYDNS 服務查詢

# 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.]\+'

4. wget 替代方案

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

5. DNS 反查工具

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

# dig (OpenDNS 解析器)
dig +short myip.opendns.com @resolver1.opendns.com

6. Bash 腳本整合範例

#!/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"

服務商可用性對比

公網 IP 查詢示意

生產環境建議:部署內部 IP 回報服務 (如 echo $SSH_CLIENT | awk '{print $1}' 配合定時任務),避免依賴外部公共 API。
copyright © 萬盛學電腦網 all rights reserved
服務格式穩定性頻率限制備註
icanhazip.comtext高低極簡
ipinfo.iotext/json高免費 5萬/天含地理位置
ifconfig.metext/json/xml/all中有功能最全
OpenDNS digtext極高無企業級解析器