IP geolocation in Python
Get the location, network and time zone of any IPv4 or IPv6 address in Python with requests: a reusable client, retries on 429, batch lookups and caching.
This guide builds a small IP geolocation client in Python. It looks up the country, city, coordinates, time zone and network of any IPv4 or IPv6 address, retries politely when it hits the rate limit, looks up many addresses in one request and caches answers. It needs Python 3.8 or newer and the requests package.
Setup
python3 -m pip install requests export IPIDB_KEY=your_api_key
The key comes from the IPIDB dashboard. The free plan allows 1,000 lookups a day and one request per second.
One lookup
import os
import requests
r = requests.get(
"https://api.ipidb.com/v1/ip/8.8.8.8",
headers={"X-API-Key": os.environ["IPIDB_KEY"]},
timeout=5,
)
data = r.json()
if data.get("success"):
loc = data["location"]
print(loc["city"], loc["country_code"], loc["latitude"], loc["longitude"])
print(data["timezone"]["id"], data["network"]["asn"], data["network"]["isp"])
else:
print(r.status_code, data["error"]["code"])The response has three main objects. location holds the continent, country, region, city, postal code, coordinates and the accuracy radius in kilometres. timezone.id is an IANA name such as America/Los_Angeles. network holds the ASN, ISP, organisation, domain and connection type. Every field is described in the field reference.
A client class with retries
A requests.Session reuses the TLS connection, which makes many lookups noticeably faster. The class below waits and retries once when the API answers 429 rate_limited, and gives up on any other error.
import os import time from functools import lru_cache import requests API = "https://api.ipidb.com/v1" class IPIDBError(Exception): def __init__(self, status, code): super().__init__(f"{status} {code}") self.status = status self.code = code class IPIDB: def __init__(self, key=None, timeout=5): self.s = requests.Session() self.s.headers["X-API-Key"] = key or os.environ["IPIDB_KEY"] self.timeout = timeout def _call(self, method, path, **kw): for attempt in range(2): r = self.s.request(method, API + path, timeout=self.timeout, **kw) data = r.json() if r.status_code == 429 and data["error"]["code"] == "rate_limited" and attempt == 0: time.sleep(float(r.headers.get("Retry-After", 1))) continue if not data.get("success"): raise IPIDBError(r.status_code, data["error"]["code"]) return data def ip(self, address, fields=None): params = {"fields": ",".join(fields)} if fields else None return self._call("GET", f"/ip/{address}", params=params) def batch(self, addresses): """Paid plans: up to 100 addresses on Starter and Pro, 1,000 on Business.""" return self._call("POST", "/ip/batch", json={"ips": list(addresses)})["results"] client = IPIDB() @lru_cache(maxsize=10000) def country_of(address): return client.ip(address, fields=["location.country_code"])["location"]["country_code"] if __name__ == "__main__": print(client.ip("2606:4700:4700::1111")["network"]["isp"]) print(country_of("1.1.1.1"))
lru_cache keeps answers in memory for the life of the process. For a web application with several workers use a shared cache such as Redis with a time to live of a day.
Many addresses at once
On paid plans POST /v1/ip/batch takes a list of addresses and returns one result per address, in the same order. An invalid address fails inside its own result and does not fail the request, so always check success on each item:
from ipidb_client import client for item in client.batch(["8.8.8.8", "1.1.1.1", "not-an-ip"]): if item["success"]: print(item["ip"], item["location"]["country_code"]) else: print(item["ip"], "error:", item["error"]["code"])
On the free plan, loop over the addresses with client.ip() instead; the retry in _call keeps you inside one request per second.
Enriching a log file
A common job is adding the country to every line of an access log. Read the unique addresses first, look each one up once, then write the result:
import re import sys from ipidb_client import country_of, IPIDBError ip_re = re.compile(r"^(\S+)") for line in sys.stdin: m = ip_re.match(line) try: cc = country_of(m.group(1)) if m else "-" except IPIDBError as e: if e.code == "quota_exceeded": sys.exit("quota used up") cc = "?" print(cc, line, end="")
Run it as python3 enrich_log.py < access.log > access-with-country.log.
Next steps
The same client works for the blacklist and MAC vendor endpoints: call client._call("GET", "/blacklist/1.2.3.4") or "/mac/00:1A:2B:3C:4D:5E". All three APIs share one key and one quota.
Related
- API documentation: every endpoint, field and error code
- IPIDB APIs: IP data, blacklist and MAC vendor lookups
- Pricing: the free plan and what paid plans add
- IP geolocation in PHP
- IP geolocation in Node.js
- IP geolocation in Go
- Block countries in nginx with an MMDB database
- Detect VPN and proxy logins