Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 終端獲取公網 IP 完整指南:curl/wget/host/dig 多種方法與腳本化示例

編輯:Linux 教學

無圖形界面的服務器、極簡容器、自動化腳本中,快速獲取本機公網 IP 是常見需求。本文匯總 curl、wget、host、dig 等工具調用公共 IP 服務接口的多種方式,涵盖純文本、JSON、XML 格式,並提供可直接嵌入腳本的變量賦值示例。

一、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

均直接輸出類似 203.0.113.45 的純 IP 地址,適合管道處理。

二、curl 結構化輸出

JSON 格式

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

XML 格式

curl ifconfig.me/all.xml

所有可用字段

curl ifconfig.me/all

三、DynDNS 風格接口(需解析)

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 替代方案

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

-qO- 靜默輸出到 stdout,echo 換行美化。

五、DNS 工具法(無需 HTTP 服務)

host -t a dartsclink.com | sed 's/.*has address //'
dig +short myip.opendns.com @resolver1.opendns.com

利用 OpenDNS 解析器返回查詢者 IP,穩定性極高。

六、Bash 腳本嵌入示例

#!/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 防止掛起。
  • 多準備 2-3 個備用源,避免單點失效。
  • 內網機器無公網 IP 時,上述方法返回 NAT 出口 IP,而非內網 IP。
Copyright © Windows教程網 All Rights Reserved