nadzoring.network_base.geolocation_ip module¶
Geographic IP lookup via ip-api.com.
Typical usage:
from nadzoring.network_base.geolocation_ip import geo_ip
result = geo_ip("8.8.8.8")
if not result:
print("Geolocation failed")
else:
print(result["country"]) # "United States"
print(result["city"]) # "Mountain View"
print(result["lat"]) # "37.386"
print(result["lon"]) # "-122.0838"
- nadzoring.network_base.geolocation_ip.GeoResult¶
Dict with keys
lat,lon,country,city(all strings).alias of
dict[str,str]
- nadzoring.network_base.geolocation_ip._fetch_geo_data(ip: str) dict | None[source]¶
Fetch raw JSON from ip-api.com for ip.
- Parameters:
ip – IPv4 or IPv6 address string.
- Returns:
Parsed JSON dict on success,
Noneon network or parse failure.
- nadzoring.network_base.geolocation_ip._parse_geo_response(data: dict, ip: str) dict[str, str] | None[source]¶
Validate and extract fields from ip-api response dict.
- Parameters:
data – Raw JSON dict from ip-api.com.
ip – Original IP address (used for logging only).
- Returns:
GeoResulton success,Nonewhen the API signals failure.
- nadzoring.network_base.geolocation_ip.geo_ip(ip: str) dict[str, str][source]¶
Retrieve geographic information for a given public IP address.
Queries the ip-api.com JSON API and returns a flat dictionary with location data. Returns an empty dict on any network or parse error so that callers can use a simple truthiness check:
result = geo_ip("8.8.8.8") if not result: # handle failure ...
Note
ip-api.com rate-limits free callers to 45 requests per minute. Private / reserved IP addresses (e.g.
192.168.x.x) will return an empty dict because the API rejects them.- Parameters:
ip – IPv4 or IPv6 address to geolocate.
- Returns:
GeoResultdict with string keyslat,lon,country, andcitywhen the lookup succeeds, or an empty dict{}on failure.
Examples
Successful lookup:
result = geo_ip("8.8.8.8") assert "lat" in result and "lon" in result print(f"{result['city']}, {result['country']}")
Handling failure (private IP, network error, rate-limit):
result = geo_ip("192.168.1.1") if not result: print("Geolocation not available")
Using results for logging / display:
for ip in ["8.8.8.8", "1.1.1.1", "9.9.9.9"]: geo = geo_ip(ip) location = f"{geo['city']}, {geo['country']}" if geo else "unknown" print(f"{ip} → {location}")