Metadata-Version: 2.5
Name: country-geoip
Version: 0.1.0
Summary: A small local IP-to-country database
Requires-Python: >=3.12
Requires-Dist: pycountry>=26.2.16
Description-Content-Type: text/markdown

# country-geoip

A small Python 3.12 package for local IPv4/IPv6 country lookups.

## Installation

Install the package from PyPI with `uv`:

```console
uv add country-geoip
```

The runtime performs no network requests. A separate command downloads the
five Regional Internet Registry (RIR) delegated-statistics files and compiles
them into an indexed SQLite database.

## Build the database

Build or refresh the local database with the installed command:

```console
country-geoip-build --output country-ip.db
```

When running directly from the repository, the equivalent command is
`python -m country_geoip.builder --output country-ip.db`.

The source files are updated regularly, so rebuild the database periodically
(weekly is normally sufficient for this use case). The builder writes to a
temporary file and atomically replaces the old database only after a successful
build. Restart long-running application workers after replacing the database so
their read-only connections reopen the new file.

## Look up addresses

```python
from country_geoip import CountryDatabase

geoip = CountryDatabase("country-ip.db")

assert geoip.lookup("8.8.8.8") == "US"
print(geoip.lookup("2001:4860:4860::8888"))
```

The result is an uppercase two-letter country code. Invalid, private,
loopback, multicast and unknown addresses return `None`.

There is also a command-line interface:

```console
country-geoip --database country-ip.db 8.8.8.8
```

Output: `US (United States)`

The command displays both the ISO code and the full country name. The Python API
continues to return the two-letter code.

## What “country” means

This database uses the public
[NRO delegated statistics format](https://www.apnic.net/about-apnic/corporate-documents/documents/resource-guidelines/rir-statistics-exchange-format/).
Its country is the country associated with the address allocation. It is a
simple and useful approximation, not the physical location of a device.
Measurement research has found this allocation country consistent with the
measured country of use for roughly 98% of examined prefixes. This package has
not been independently benchmarked, and accuracy varies by network and registry.

This approach intentionally has no API key, account, or runtime network
dependency. A commercial or actively curated geolocation feed can be more
accurate for internationally moved ranges, cloud providers and anycast
networks.

## Example usage

- [`examples/basic_usage.py`](https://github.com/diversen/country-ip/blob/main/examples/basic_usage.py)
  shows a lookup and a simple country check.

## Development

Run the tests with:

```console
python -m unittest discover -v
```
