惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LINUX DO - 最新话题
Cyberwarzone
Cyberwarzone
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Securelist
V2EX - 技术
V2EX - 技术
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy & Cybersecurity Law Blog
Spread Privacy
Spread Privacy
N
News and Events Feed by Topic
H
Heimdal Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
大猫的无限游戏
大猫的无限游戏
L
LangChain Blog
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
G
GRAHAM CLULEY
L
Lohrmann on Cybersecurity
G
Google Developers Blog
Recorded Future
Recorded Future
H
Hacker News: Front Page
Application and Cybersecurity Blog
Application and Cybersecurity Blog
The GitHub Blog
The GitHub Blog
量子位
V
V2EX
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Vercel News
Vercel News
H
Help Net Security
Know Your Adversary
Know Your Adversary
Forbes - Security
Forbes - Security
T
Threatpost
S
SegmentFault 最新的问题
Hugging Face - Blog
Hugging Face - Blog
T
Threat Research - Cisco Blogs
人人都是产品经理
人人都是产品经理
Project Zero
Project Zero
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
罗磊的独立博客
C
Check Point Blog
P
Palo Alto Networks Blog
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
Apple Machine Learning Research
Apple Machine Learning Research
C
Cybersecurity and Infrastructure Security Agency CISA
A
Arctic Wolf

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Getting the public IP in Python — scripts, Django, FastAPI
Vix · 2026-06-15 · via DEV Community

Vix

Getting the public IP in Python — scripts, Django, FastAPI

Whether you're writing a quick script, building a Django web app, or designing a FastAPI microservice, knowing the public IP of your server or client is a recurring need. This article covers all three scenarios with practical code, using IPPubblico.org — a free API with no key required, HTTPS, and CORS enabled.


Why IPPubblico?

Before diving into code, here's a quick summary of why it's worth using:

  • No API key — works immediately, zero setup
  • HTTPS only — secure by default
  • Plain text endpoint — no parsing for simple cases
  • Full JSON endpoint — city, country, ISP, ASN, timezone when needed
  • No hard rate limit — soft limiting applies for abuse prevention
  • Commercial use allowed on the free tier

Use case 1 — Simple script with requests

The most common scenario: a standalone script that needs to know its own public IP.

import requests

def get_public_ip():
    try:
        response = requests.get(
            'https://ipv4.ippubblico.org/',
            timeout=5
        )
        response.raise_for_status()
        return response.text.strip()
    except requests.RequestException as e:
        print(f"Failed to get IP: {e}")
        return None

if __name__ == '__main__':
    ip = get_public_ip()
    print(f"Public IP: {ip}")
    # Public IP: 203.0.113.42


Use case 2 — Full geolocation with requests

When you need country, city, ISP and timezone in addition to the IP:

import requests
from dataclasses import dataclass
from typing import Optional

@dataclass
class IPInfo:
    ip: str
    country: Optional[str]
    country_code: Optional[str]
    city: Optional[str]
    region: Optional[str]
    isp: Optional[str]
    timezone: Optional[str]
    lat: Optional[float]
    lon: Optional[float]

def get_ip_info(ip: str = None) -> Optional[IPInfo]:
    """
    Get geolocation info for an IP address.
    If ip is None, returns info for the current public IP.
    """
    url = 'https://ippubblico.org/?api=1'
    if ip:
        url += f'&ip={ip}'

    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        data = response.json()

        if data.get('status') != 'ok':
            return None

        geo = data.get('geo', {})
        return IPInfo(
            ip=data.get('ip', ''),
            country=geo.get('country'),
            country_code=geo.get('country_code'),
            city=geo.get('city'),
            region=geo.get('region'),
            isp=data.get('isp'),
            timezone=data.get('timezone'),
            lat=geo.get('lat'),
            lon=geo.get('lon'),
        )
    except requests.RequestException as e:
        print(f"Request failed: {e}")
        return None

if __name__ == '__main__':
    info = get_ip_info()
    if info:
        print(f"IP:       {info.ip}")
        print(f"Country:  {info.country} ({info.country_code})")
        print(f"City:     {info.city}, {info.region}")
        print(f"ISP:      {info.isp}")
        print(f"Timezone: {info.timezone}")


Use case 3 — Async script with httpx

For async Python scripts using httpx:

import asyncio
import httpx

async def get_public_ip() -> str | None:
    async with httpx.AsyncClient(timeout=5.0) as client:
        try:
            response = await client.get('https://ipv4.ippubblico.org/')
            response.raise_for_status()
            return response.text.strip()
        except httpx.HTTPError as e:
            print(f"Failed to get IP: {e}")
            return None

async def get_ip_info() -> dict | None:
    async with httpx.AsyncClient(timeout=5.0) as client:
        try:
            response = await client.get('https://ippubblico.org/?api=1')
            response.raise_for_status()
            data = response.json()
            return data if data.get('status') == 'ok' else None
        except httpx.HTTPError as e:
            print(f"Failed to get IP info: {e}")
            return None

async def main():
    ip = await get_public_ip()
    print(f"Public IP: {ip}")

    info = await get_ip_info()
    if info:
        print(f"Country: {info['geo']['country']}")
        print(f"City:    {info['geo']['city']}")

asyncio.run(main())


Use case 4 — Django middleware for country detection

A Django middleware that detects the user's country on every request and adds it to request.country_code. Useful for region-based content, currency selection, or logging.

# myapp/middleware.py

import requests
from django.core.cache import cache

CACHE_TIMEOUT = 3600  # 1 hour per IP

class CountryDetectionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        client_ip = self._get_client_ip(request)
        request.client_ip = client_ip
        request.country_code = self._get_country(client_ip)
        response = self.get_response(request)
        return response

    def _get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            return x_forwarded_for.split(',')[0].strip()
        return request.META.get('REMOTE_ADDR')

    def _get_country(self, ip: str) -> str | None:
        if not ip:
            return None

        cache_key = f'country_{ip}'
        cached = cache.get(cache_key)
        if cached:
            return cached

        try:
            response = requests.get(
                'https://ippubblico.org/?api=1',
                timeout=3
            )
            data = response.json()
            country_code = data.get('geo', {}).get('country_code')
            if country_code:
                cache.set(cache_key, country_code, CACHE_TIMEOUT)
            return country_code
        except Exception:
            return None

Register it in settings.py:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'myapp.middleware.CountryDetectionMiddleware',  # add here
    # ... rest of middleware
]

Use it in any view:

# views.py

from django.http import JsonResponse

def my_view(request):
    return JsonResponse({
        'ip': request.client_ip,
        'country': request.country_code,
    })


Use case 5 — Django view with per-request geolocation

For cases where you need full geolocation data in a specific view, not globally:

# views.py

import requests
from django.http import JsonResponse
from django.views import View

class UserLocationView(View):
    def get(self, request):
        ip = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')[0].strip() \
             or request.META.get('REMOTE_ADDR')

        try:
            response = requests.get(
                'https://ippubblico.org/?api=1',
                timeout=5
            )
            data = response.json()
            geo = data.get('geo', {})

            return JsonResponse({
                'ip': data.get('ip'),
                'country': geo.get('country'),
                'country_code': geo.get('country_code'),
                'city': geo.get('city'),
                'timezone': data.get('timezone'),
            })
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)


Use case 6 — FastAPI dependency injection

The cleanest FastAPI pattern: a reusable dependency that injects IP info into any route.

# dependencies.py

import httpx
from functools import lru_cache
from fastapi import Request, Depends
from typing import Optional
from pydantic import BaseModel

class GeoInfo(BaseModel):
    city: Optional[str] = None
    region: Optional[str] = None
    country: Optional[str] = None
    country_code: Optional[str] = None
    lat: Optional[float] = None
    lon: Optional[float] = None

class IPInfo(BaseModel):
    ip: str
    isp: Optional[str] = None
    timezone: Optional[str] = None
    geo: GeoInfo = GeoInfo()

def get_client_ip(request: Request) -> str:
    forwarded = request.headers.get('X-Forwarded-For')
    if forwarded:
        return forwarded.split(',')[0].strip()
    return request.client.host

async def get_ip_info(request: Request) -> Optional[IPInfo]:
    ip = get_client_ip(request)
    async with httpx.AsyncClient(timeout=5.0) as client:
        try:
            response = await client.get('https://ippubblico.org/?api=1')
            data = response.json()
            if data.get('status') == 'ok':
                return IPInfo(**{
                    'ip': data.get('ip', ip),
                    'isp': data.get('isp'),
                    'timezone': data.get('timezone'),
                    'geo': GeoInfo(**data.get('geo', {}))
                })
        except Exception:
            pass
    return None

Use in any route:

# main.py

from fastapi import FastAPI, Depends
from dependencies import IPInfo, get_ip_info

app = FastAPI()

@app.get('/location')
async def location(ip_info: IPInfo = Depends(get_ip_info)):
    if not ip_info:
        return {'error': 'Could not detect location'}
    return {
        'ip': ip_info.ip,
        'country': ip_info.geo.country,
        'city': ip_info.geo.city,
        'timezone': ip_info.timezone,
    }


Use case 7 — FastAPI with caching (Redis)

For high-traffic APIs, cache the geolocation result per IP to avoid repeated external calls:

# dependencies_cached.py

import httpx
import json
from fastapi import Request
from typing import Optional
import redis.asyncio as redis

redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
CACHE_TTL = 3600  # 1 hour

async def get_ip_info_cached(request: Request) -> Optional[dict]:
    forwarded = request.headers.get('X-Forwarded-For')
    ip = forwarded.split(',')[0].strip() if forwarded else request.client.host

    cache_key = f'ipinfo:{ip}'
    cached = await redis_client.get(cache_key)
    if cached:
        return json.loads(cached)

    async with httpx.AsyncClient(timeout=5.0) as client:
        try:
            response = await client.get('https://ippubblico.org/?api=1')
            data = response.json()
            if data.get('status') == 'ok':
                await redis_client.setex(cache_key, CACHE_TTL, json.dumps(data))
                return data
        except Exception:
            pass
    return None


Handling rate limits

If your application makes many requests from the same IP in a short period, you may receive a 429 Too Many Requests response. The API returns a Retry-After header indicating how many seconds to wait:

import time
import requests

def get_ip_with_retry(max_retries: int = 3) -> str | None:
    for attempt in range(max_retries):
        response = requests.get(
            'https://ipv4.ippubblico.org/',
            timeout=5
        )

        if response.status_code == 200:
            return response.text.strip()

        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 20))
            print(f"Rate limited. Waiting {retry_after}s before retry {attempt + 1}/{max_retries}")
            time.sleep(retry_after)
            continue

        response.raise_for_status()

    return None

In practice, caching results at the application level eliminates most rate limit concerns.


Quick reference

Need Endpoint Response
IPv4 only https://ipv4.ippubblico.org/ 203.0.113.42
IPv6 only https://ipv6.ippubblico.org/ 2001:db8::1 or NONE
Both protocols https://ippubblico.org/?text=1 IPv4: x\nIPv6: x
Full geolocation https://ippubblico.org/?api=1 JSON with country, city, ISP

Full API documentation: ippubblico.org/docs.html


Conclusion

IPPubblico covers the full range of Python use cases — from a one-liner in a shell script to a properly typed FastAPI dependency with Redis caching. The consistent API across plain text and JSON endpoints means you can start simple and add complexity only when you need it.

The Django middleware and FastAPI dependency patterns shown here are production-ready starting points: they handle client IP extraction behind proxies, cache results to avoid redundant API calls, and fail gracefully when the external service is unavailable.


Using a different approach for IP detection in Python? Share it in the comments.