Metadata-Version: 2.5
Name: vpndetection
Version: 6.3.0
Summary: Official Python client library for the VPNDetection API. Detect VPNs, proxies, Tor, hosting and CDN IPs.
Project-URL: Homepage, https://vpndetection.io
Project-URL: Documentation, https://docs.vpndetection.io
Project-URL: Source, https://github.com/vpndetection-io/sdk-python
Project-URL: Issues, https://github.com/vpndetection-io/sdk-python/issues
Author-email: Mslm Dev <support@vpndetection.io>
License-Expression: MIT
License-File: LICENSE
Keywords: cdn,datacenter-proxy,fraud-prevention,hosting,ip-geolocation,ip-intelligence,mobile-proxy,proxy-detection,relay,residential-proxy,tor,vpn,vpn-detection
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Internet
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: attrs>=22.2.0
Requires-Dist: cachetools>=5.3
Requires-Dist: httpx<1,>=0.27
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: openapi-python-client<0.30,>=0.29; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# [<img src="https://s3.vpndetection.io/vpndetection-public/brand/mark.svg" alt="VPNDetection" height="28"/>](https://vpndetection.io/) VPNDetection Python Client Library

[![PyPI](https://img.shields.io/pypi/v/vpndetection.svg)](https://pypi.org/project/vpndetection/)
[![license](https://img.shields.io/pypi/l/vpndetection.svg)](LICENSE)

The official Python client library for the [VPNDetection](https://vpndetection.io) API.

It tells you whether an IP address is a VPN, residential proxy, Tor node, relay or hosting server.

## Getting Started

```bash
pip install vpndetection
```

Requires Python 3.11 or newer. Type hints are included, and the package ships `py.typed`.

## Usage

**Start with a free API key**, no card needed: create one in the [console](https://app.vpndetection.io) and pass it in. A free key answers the core answer on its organization's quota: `ip`, `is_vpn`, Tor and relay detection with their detail, `is_anycast`, `hostname` (the reverse DNS name), country-level `location` and `asn` with the AS's country and RPKI status, without its `type`. Past the quota, each lookup raises `quota_exceeded` until the quota resets. The Data plan answers every field, the hosting, CDN and proxy flags and the provider behind each flag among them, at the volume you need ([pricing](https://vpndetection.io/pricing)).

```python
import os

from vpndetection import VPNDetection, VPNDetectionError

client = VPNDetection(os.environ["VPNDETECTION_API_KEY"])

try:
    result = client.lookup("45.83.91.1")
    print(result.is_vpn)              # True
    print(result.location.country)    # the ISO 3166 country code
    print(result.asn.name)            # who runs the announcing network
except VPNDetectionError as err:
    if err.kind != "quota_exceeded":
        raise
    # The organization's quota is spent: no lookup is answered until it resets.
    print(err.message)
```

The client holds an HTTP connection pool, so use it as a context manager, or call `client.close()` when you are done with it:

```python
with VPNDetection(os.environ["VPNDETECTION_API_KEY"]) as client:
    print(client.lookup("45.83.91.1").is_vpn)
```

### On the Data plan

The Data plan answers every field: `is_hosting`, `is_cdn` and the five proxy flags as well (`is_ispproxy` and its detail `ispproxy` flag an ISP proxy: a proxy server in a datacenter, on address space an internet service provider registers or announces), the carrier and satellite flags, the five service flags (SSH, SMTP, web, DNS resolver and BitTorrent), `is_bot` (whether a bot such as a crawler uses the address) and `bot` (whose bot it is and whether its operator vouches for the address), the AS's `type` (isp, hosting, education, government or business), city-level `location`, the `company` and the `abuse` contact, and the provider (its ID and its name), confidence and last-seen detail behind each flag. Paid plans differ by quota alone. The same call and the same key, with more in the answer:

```python
result = client.lookup("45.83.91.1")
print(result.is_vpn)              # True
print(result.is_hosting)          # True
print(result.vpn.provider)        # 'nordvpn'
```

### Async

Everything above works the same way under asyncio, with `AsyncVPNDetection`:

```python
import asyncio
import os

from vpndetection import AsyncVPNDetection

async def main():
    async with AsyncVPNDetection(os.environ["VPNDETECTION_API_KEY"]) as client:
        result = await client.lookup("45.83.91.1")
        print(result.is_vpn)   # True

asyncio.run(main())
```

### Your own address

```python
result = client.my_ip()
print(result.ip)   # the address we saw this call come from
```

Same answer `lookup` would give for that address, and it counts against your organization's quota the same way. It is deliberately not cached: which address you are is the whole question, and a machine that moves between networks would otherwise be told where it used to be.

### Your plan and usage

```python
acct = client.my_entitlement()
print(acct.plan.name)         # Data, what to show
print(acct.plan.key)          # data_4, what to compare against
print(acct.usage.requests)    # 580
print(acct.usage.window_end)  # when the quota resets
```

Usage counts against your organization's quota, from `window_start` to `window_end`: the same number a lookup is gated on. `hard_limit` is where answers stop (on the free plan, the quota); `None` means never, the normal state of a paid plan with no overage cap, which is not the same as zero.

Both are on the async client too: `await client.my_ip()` and `await client.my_entitlement()`.

### Batch lookup

Look up as many addresses as you like at once. Bogons and cached answers are handled locally, and everything else goes to the batch endpoint in chunks of up to 1000 addresses, in parallel. The batch endpoint needs a paid plan:

```python
results = client.lookup_batch(["45.83.91.1", "8.8.8.8", "1.1.1.1"])

for ip, result in results.items():
    if isinstance(result, Exception):
        print(f"{ip}: {result}")
        continue
    print(f"{ip}: {result.is_vpn}")
```

Results are keyed by address, in the order you first listed each one, so duplicates in your list collapse into a single entry and one address failing never loses the rest: it carries its error as its value, with the status the API would have given that address on its own. An address a spent quota refuses carries `quota_exceeded`. An entry whose `cap_reached` is true (none is today) is that entry's [`CappedAnswerError`](#errors), and its `result` holds the answer.

How many chunks are in flight at once, how many times a failed chunk is retried and how long each request may take are configurable per call:

```python
results = client.lookup_batch(many_ips, concurrency=4, retries=4, timeout=30)
```

### Is that crawler who it says it is?

Pass the `User-Agent` the visitor sent, and on a paid plan the answer's `user_agent` says which client it names and whether this address is it: `verified` when its operator vouches for the address, `spoofed` when it does not, `unverifiable` for a bot nothing published can confirm, and `not_bot` for a browser, an app or a script. A batch takes a map from address to agent, and an address with none sends none. A free key's answer never carries `user_agent`.

```python
result = client.lookup("66.249.66.1", user_agent=request_user_agent)
if result.user_agent is not None and result.user_agent.verdict == "verified":
    print(f"a real {result.user_agent.agent}")

results = client.lookup_batch(
    ["66.249.66.1", "45.83.91.1"],
    user_agents={"66.249.66.1": "Googlebot/2.1 (+http://www.google.com/bot.html)"},
)
```

An answer for an address and an agent is cached apart from the address's plain answer and from another agent's. An empty agent sends none, and a bogon carries none.

### Caching

Answers are cached by default, so repeat lookups of the same address are free:

```python
client = VPNDetection(os.environ["VPNDETECTION_API_KEY"])

result = client.lookup("45.83.91.1")
print(result.is_vpn)    # True, API request

result2 = client.lookup("45.83.91.1")
print(result2.is_vpn)   # True, no API request, result was cached
```

You can change the default cache variables (max size, TTL in seconds, etc) on initialization, or even disable it:

```python
client = VPNDetection(
    os.environ["VPNDETECTION_API_KEY"], cache_max_size=50_000, cache_ttl=6 * 60 * 60
)
client_no_cache = VPNDetection(os.environ["VPNDETECTION_API_KEY"], cache=False)
```

### Private and reserved addresses

Private, loopback, link-local, documentation and multicast addresses (and their IPv6 equivalents, including the 6to4 and Teredo ranges) can never be VPN or proxy infrastructure. The library answers them locally, so they cost no request and no quota:

```python
result = client.lookup("192.168.1.1")
result.is_bogon   # True, this answer was computed rather than served
result.is_vpn     # False
```

The check is available on the client, which is handy when your inputs are addresses anyway:

```python
client.is_bogon("10.0.0.1")   # True
client.is_bogon("8.8.8.8")    # False
```

It is also importable on its own, if you want it without a client:

```python
from vpndetection import is_bogon

is_bogon("10.0.0.1")   # True
```

### Errors

Failures raise a `VPNDetectionError` carrying a `kind` and a `retryable` flag:

```python
from vpndetection import VPNDetectionError

try:
    client.lookup("1.1.1.1")
except VPNDetectionError as err:
    print(err.kind, err.retryable)
```

`kind` is one of `bad_request`, `unauthorized`, `forbidden`, `rate_limited`, `quota_exceeded`, `server_error` or `network`.

**A capped answer raises.** The API answers a spent quota with a `429`, raised as `quota_exceeded`. An answer whose `cap_reached` is true (none is today) raises `CappedAnswerError`, a `VPNDetectionError` of kind `quota_exceeded`, not retryable, with `status` 200 and the answer as `err.result`, so a program fails where it can be seen and a `catch` still has the answer. This covers `lookup`, `my_ip` and every entry of `lookup_batch`, fresh or from the cache, which holds such an answer for at most a minute and raises it again on each hit. No client option turns it off. A private address never raises it.

```python
from vpndetection import CappedAnswerError

try:
    client.lookup("45.83.91.1")
except CappedAnswerError as err:
    answer = err.result          # the answer the API served
```

In `lookup_batch` an entry's value is that error, as a failing address's is, and the batch returns:

```python
for ip, answer in client.lookup_batch(["45.83.91.1", "8.8.8.8"]).items():
    if isinstance(answer, CappedAnswerError):
        print(ip, answer.kind)       # quota_exceeded, with answer.result holding the answer
```

A spent quota's `429` `quota_exceeded` is the bare `VPNDetectionError` with no `result`.

**Added in 6.1.0:** `CappedAnswerError`. In 6.0.0 a capped answer raised the bare `VPNDetectionError`, with the same `kind`, `status` and `result`, so an `except VPNDetectionError` or a check on `kind` written for it still catches this one.

A request that runs past its `timeout` fails with `network`. The default is 30 seconds per attempt, body included, so a retried call can take longer in total, and a database download is exempt. Set it on the client, or on a single `lookup`, `my_ip`, `my_entitlement`, `lookup_batch`, `oauth` or `database` call (the last from 5.4.0, transfers aside):

```python
client = VPNDetection(os.environ["VPNDETECTION_API_KEY"], timeout=30)
result = client.lookup("45.83.91.1", timeout=2)
```

`None` means no bound on the client, and the client's own on a call. Anything else that is not a number greater than 0 raises `ValueError` where it is set, before any request is made.

**Changed in 5.3.0:** a timeout of 0 or less, NaN, infinity or a string used to be accepted, and then failed every call.

Note that `rate_limited` and `quota_exceeded` both arrive as HTTP 429 and are not the same thing. A rate limit carries `Retry-After`: the API faces extreme traffic bursts, and retrying later works. One without it is `quota_exceeded`: your organization's quota is spent (or a paid key's overage cap is reached), and that lasts until the quota resets. The library retries rate limits for you, but never `quota_exceeded`: it is sent once and raised with the API's message.

### Database downloads

If your key carries the `db.download` scope, the licensed databases are available through `client.database`. `list` answers database families, and the IDs the other calls take come from each family's `versions`. There are three ways to get a database: the time-limited link, the bytes, or straight to a file, which streams so nothing bigger than a chunk is ever held in memory:

```python
databases = client.database.list()

url = client.database.download_url("vpn_ip_extended_v1", "mmdb")
raw = client.database.download_bytes("cdn_ip_v1", "csvgz")
written = client.database.download("vpn_ip_extended_v1", "mmdb", "./vpn_ip_extended_v1.mmdb")
```

`DATABASE_FORMATS`, `STANDINGS` and `LICENSE_TYPES` hold the published formats and the values a family's `standing` and `license_type` can take, at runtime, for checking one that came from a flag or a form before you make a call.

`download_bytes` holds the whole file in memory, and the catalog runs from `cdn_ip_v1` at 10 KB to `resproxy_ip_90d_v1` at 1.79 GB, so use `download` for anything you have not measured.

From 5.13.0, each of the three takes a keyword-only `build`: the build a `database.updated` webhook names, so the file is the one whose `sha256` the webhook carries rather than whatever is live by the time you ask. Without it you get the live build. A build is kept 7 days, and one pruned since is a `bad_request` with status 410:

```python
data = event["data"]  # a database.updated webhook's
client.database.download(data["dataset"], "mmdb", f"./{data['dataset']}.mmdb", build=data["build"])
```

From 5.4.0, `list`, `metadata`, `checksums`, `downloads` and `download_url` each take a keyword-only `timeout` in seconds, bounding each attempt at that one call in place of the client's:

```python
catalog = client.database.list(timeout=5)
sums = client.database.checksums("vpn_ip_extended_v1", "mmdb", timeout=5)
```

`download` and `download_bytes` deliberately take no `timeout` and raise `TypeError` if handed one, rather than accepting it and quietly doing nothing: a transfer runs to gigabytes and minutes, so any bound that suits a JSON call would abandon a healthy download. `download_url` does take one, because minting the link is an ordinary API request - it bounds that request, not whatever you do with the link afterwards.

### Sign in with OAuth (device flow)

A program running on someone's own machine can let them sign in with a browser and pick one of their API keys, instead of asking them to paste it:

```python
from vpndetection import VPNDetection

with VPNDetection() as signin:  # no key yet: the sign-in hands one over
    device = signin.oauth.device_authorization(
        "your-client-id", scope="account.read apikeys.read apikeys.reveal"
    )
    print(f"Open {device.verification_uri} and enter {device.user_code}")
    tokens = signin.oauth.poll_device_token("your-client-id", device)

if tokens.apikey is None:
    raise SystemExit("No API key was picked")
client = VPNDetection(tokens.apikey)
```

A refusal raises `OauthAccessDeniedError` and a code that ran out raises `OauthExpiredTokenError`. `client.oauth.revoke("your-client-id", tokens.refresh_token)` signs the machine out. Only a client we registered, such as our CLI, can use the device flow: an app of your own signs people in with the authorization code flow below.

### Sign in with OAuth (authorization code)

An app that can take a browser redirect signs the person in there instead, with a PKCE pair made for that one sign-in:

```python
from vpndetection import VPNDetection

signin = VPNDetection()  # no key yet: the sign-in hands one over
redirect_uri = "http://127.0.0.1:8765/callback"
pkce = signin.oauth.create_pkce()

url = signin.oauth.authorization_url(
    "your-client-id", redirect_uri, pkce.challenge, scope="apikeys.use", state="your-state"
)
# Open url in the browser. Its redirect to redirect_uri carries code and state.
tokens = signin.oauth.exchange_authorization_code("your-client-id", code, pkce.verifier, redirect_uri)
```

Check that `state` came back as you sent it before you exchange `code`, which works once. The client ID can also be the https URL of a client metadata document your app serves, and such an app is never handed a key, so `tokens.apikey` stays `None`.

### Register a client

An app with no client ID, and no client metadata document to use as one, registers itself, then signs in with the `client_id` it gets back as the client ID for `authorization_url` and `exchange_authorization_code`:

```python
client = VPNDetection()  # no key yet: the sign-in hands one over
registration = client.oauth.register(["http://127.0.0.1:8765/callback"], client_name="Your App")
```

Each redirect URI must be https on a public host name, or http on a loopback address, which then matches any port. Nothing is kept until a person approves the client, so an app with no client ID saved can simply register again.

### Fields your plan does not include

A free key's answers leave out `is_hosting`, `is_cdn`, the five proxy flags, `is_bot`, the carrier, satellite and service flags, `bot`, `company` and `abuse`, the city and region, the AS's `type`, and of the detail behind each flag they carry only Tor's and relay's. Every answer to a key carries `cap_reached`, `false` on every answer today: a key past its organization's quota, or a paid key's overage cap, is refused with a `429` rather than answered, and an answer whose `cap_reached` is true raises `CappedAnswerError` ([above](#errors)). Those members are `None` when your key does not include them, which means "not in your plan" rather than "checked, and no". `is_vpn` is `None` the same way where an answer leaves it out, which is unknown, never clean: `result.raw` tells a served member from a missing one, and neither reads `False` or `""`.

```python
result.flagged("is_hosting")   # False rather than None on a plan without it
result.is_hosting is None      # True on the free plan: not in your plan
result.is_bot is None          # True on the free plan: not in your plan
result.asn.type is None        # True on the free plan, which leaves it out
"type" in result.raw["asn"]    # False on the free plan: it was not in the answer
"is_vpn" in result.raw         # False when an answer leaves it out: unknown, never clean
err.result.cap_reached is True # a CappedAnswerError's answer
```

## Other Libraries

There are official VPNDetection client libraries available for many languages including PHP, Python, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. See our GitHub at https://github.com/vpndetection-io for more.

## About VPNDetection

VPN Detection API: Accurate anonymity detection identifying VPNs, residential proxies, hosting servers, Tor nodes, CDNs, relays and more.

[<picture><source media="(prefers-color-scheme: dark)" srcset="https://s3.vpndetection.io/vpndetection-public/brand/logo-dark.svg"><img src="https://s3.vpndetection.io/vpndetection-public/brand/logo.svg" alt="VPNDetection" height="40"/></picture>](https://vpndetection.io/)

## License

This project is licensed under the [MIT License](LICENSE).
