萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 獲取公網 IP 地址的多種實用方法

前言

在網絡編程或系統管理任務中,獲取機器的公網 IP 地址是常見需求。Python 提供了豐富的庫來實現這一功能,本文總結了幾種主流且可靠的方法,涵蓋 HTTP API 調用、DNS 查詢及原始套接字等技術路線,供開發者根據場景選擇。

方法一:調用公共 HTTP API(推薦最簡單)

利用現成的 IP 查詢服務,如 httpbin.org、ipify.org 或國內的 ip.sb,只需發送 GET 請求並解析 JSON 或純文本響應。

import requests

def get_public_ip_via_api():
    try:
        # 使用 ipify.org,返回 JSON 格式
        resp = requests.get('https://api.ipify.org?format=json', timeout=5)
        resp.raise_for_status()
        return resp.json()['ip']
    except Exception as e:
        print(f"API 請求失敗: {e}")
        return None

if __name__ == '__main__':
    ip = get_public_ip_via_api()
    if ip:
        print(f"您的公網 IP: {ip}")

優點:代碼極簡,無需處理網絡協議細節。
缺點:依賴第三方服務可用性,請求可能被限流或封鎖。

方法二:使用 urllib 標準庫(無第三方依賴)

若不想引入 requests,可用內建 urllib.request 完成相同任務。

import urllib.request
import json

def get_public_ip_stdlib():
    url = 'https://api.ipify.org?format=json'
    try:
        with urllib.request.urlopen(url, timeout=5) as response:
            data = json.loads(response.read().decode())
            return data['ip']
    except Exception as e:
        print(f"標準庫請求失敗: {e}")
        return None

方法三:通過 DNS 查詢解析(更穩定、快速)

向 OpenDNS 或 Google DNS 發送特定域名查詢,直接獲取出口 IP。此法不依賴 Web 服務,抗幹擾能力強。

import dns.resolver

def get_public_ip_dns():
    try:
        # OpenDNS 的 myip.opendns.com 會返回查詢者的 IP
        resolver = dns.resolver.Resolver()
        resolver.nameservers = ['208.67.222.222', '208.67.220.220']  # OpenDNS
        answers = resolver.resolve('myip.opendns.com', 'A')
        return answers[0].to_text()
    except Exception as e:
        print(f"DNS 查詢失敗: {e}")
        return None

需安裝 dnspython:pip install dnspython。

方法四:原始套接字連接外部服務(底層理解)

通過建立 UDP 連接到公共 DNS(如 8.8.8.8),從套接字獲取本地綁定的出口 IP。注意:這獲取的是**路由出口 IP**,若在 NAT 後則為內網網關 IP,不一定是公網 IP。

import socket

def get_egress_ip():
    try:
        # 建立一個 UDP 連接(不發送數據),僅為觸發路由選擇
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(('8.8.8.8', 80))  # Google DNS
            return s.getsockname()[0]
    except Exception as e:
        print(f"套接字方法失敗: {e}")
        return None

方法五:綜合健壯封裝(生產環境建議)

結合多種備選源,自動重試與降級,提高可用性。

import requests
import socket
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

PUBLIC_IP_SERVICES = [
    'https://api.ipify.org?format=json',
    'https://ipinfo.io/ip',
    'https://ipv4.icanhazip.com',
]

def get_public_ip_robust():
    # 1. 嘗試 HTTP API
    for url in PUBLIC_IP_SERVICES:
        try:
            resp = requests.get(url, timeout=3)
            if resp.status_code == 200:
                ip = resp.text.strip()
                # 簡單驗證 IPv4 格式
                if all(0 <= int(part) <= 255 for part in ip.split('.')):
                    logger.info(f"通過 {url} 獲取 IP: {ip}")
                    return ip
        except Exception as e:
            logger.warning(f"服務 {url} 失敗: {e}")
    
    # 2. 回退:嘗試 DNS(需 dnspython)
    try:
        import dns.resolver
        resolver = dns.resolver.Resolver()
        resolver.nameservers = ['208.67.222.222']
        answers = resolver.resolve('myip.opendns.com', 'A')
        ip = answers[0].to_text()
        logger.info(f"通過 DNS 獲取 IP: {ip}")
        return ip
    except Exception as e:
        logger.error(f"所有方法均失敗: {e}")
    
    return None

if __name__ == '__main__':
    ip = get_public_ip_robust()
    print(f"最終獲取公網 IP: {ip or '失敗'}")

總結與建議

  • 腳本/工具快速開發:首選 方法一(requests + ipify),代碼最少、可讀性最高。
  • 無外部依賴項目:使用 方法二(標準庫 urllib)。
  • 高可用性/生產服務:採用 方法五的多源降級策略,並加入緩存機制(如 5 分鐘緩存),避免頻繁請求觸發限流。
  • 容器/雲環境:若運行在 AWS/GCP/Azure,優先使用實例元數據服務(如 https://169.254.169.254/latest/meta-data/public-ipv4),最準確且無網絡開銷。

根據具體部署環境與可靠性要求選擇合適方案,並妥善處理異常與超時,即可穩健獲取公網 IP。

copyright © 萬盛學電腦網 all rights reserved