File size: 1,384 Bytes
a42ab7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
Geolocation Utilities

Utilities for IP address geolocation lookup.
"""
import logging
from typing import Tuple, Optional
import httpx

logger = logging.getLogger(__name__)

# Geolocation API settings
GEOLOCATION_API_URL = "http://ip-api.com/json/{ip}?fields=status,country,regionName"
GEOLOCATION_TIMEOUT = 2.0  # seconds


async def get_geolocation(ip_address: str) -> Tuple[Optional[str], Optional[str]]:
    """
    Get country and region for an IP address using ip-api.com.
    
    Args:
        ip_address: IPv4 or IPv6 address
        
    Returns:
        Tuple of (country, region) or (None, None) if lookup fails
    """
    if not ip_address:
        return None, None
    
    # Skip geolocation for localhost/private IPs
    if ip_address in ("127.0.0.1", "::1", "localhost") or ip_address.startswith(("192.168.", "10.", "172.")):
        return None, None
    
    try:
        async with httpx.AsyncClient(timeout=GEOLOCATION_TIMEOUT) as client:
            response = await client.get(GEOLOCATION_API_URL.format(ip=ip_address))
            if response.status_code == 200:
                data = response.json()
                if data.get("status") == "success":
                    return data.get("country"), data.get("regionName")
    except Exception as e:
        logger.warning(f"Geolocation lookup failed for {ip_address}: {e}")
    
    return None, None