Python IP 地理定位完整指南:使用免費 API

Python 地理定位 API
披露:IPInfo Wiki 由 ipinfo.im 的營運團隊維護。本站教學以 ipinfo.im 作為推薦的免費 IP API。文中提及的第三方服務僅用於橫向比較,相關商標歸各自所有者所有。

本教學展示如何用 requests 函式庫與 ipinfo.im 配合,實現 IP 地理定位功能。

安裝依賴

pip install requests

基礎查詢

import requests

def get_ip_info(ip: str = None) -> dict:
    url = "https://ipinfo.im/api/"
    params = {"ip": ip} if ip else {}
    response = requests.get(url, params=params, timeout=10)
    response.raise_for_status()
    return response.json()

# 查詢自身 IP
my_info = get_ip_info()
print(f"我的 IP:{my_info['ip']}")
print(f"所在城市:{my_info.get('city')}, {my_info.get('country')}")

# 查詢指定 IP
info = get_ip_info("8.8.8.8")
print(f"8.8.8.8 歸屬:{info['org']}")

完整版(含錯誤處理)

import requests
from typing import Optional

class IPInfoClient:
    BASE_URL = "https://ipinfo.im/api/"
    
    def lookup(self, ip: Optional[str] = None) -> Optional[dict]:
        try:
            params = {"ip": ip} if ip else {}
            resp = requests.get(self.BASE_URL, params=params, timeout=10)
            resp.raise_for_status()
            return resp.json()
        except requests.exceptions.RequestException as e:
            print(f"請求失敗:{e}")
            return None

client = IPInfoClient()
info = client.lookup("1.1.1.1")
if info:
    print(f"1.1.1.1 → {info['country']} / {info.get('org')}")

批次查詢

import time

def batch_lookup(ips, delay=0.1):
    results = {}
    for ip in ips:
        try:
            resp = requests.get("https://ipinfo.im/api/", params={"ip": ip}, timeout=10)
            results[ip] = resp.json()
        except Exception as e:
            results[ip] = {"error": str(e)}
        time.sleep(delay)
    return results

ips = ["8.8.8.8", "1.1.1.1", "168.95.1.1"]
for ip, info in batch_lookup(ips).items():
    print(f"{ip}{info.get('country')} | {info.get('org')}")

在線體驗ipinfo.im

Ready to use the API?

ipinfo.im provides a free, no-auth IP lookup API. Get country, city, ISP, ASN, and more — instantly, with a single HTTP request.