Geolocation Compliance: Enforce Territories Despite VPNs

Abdul Mateen
By Abdul Mateen Integration Engineer
Posted on December 1, 2026 | 25 min read
Geolocation Compliance: Enforce Territories Despite VPNs
Back to All Guides

Geolocation compliance means offering content, a bet, or a service only in the places where a contract or a law allows it, based on where the visitor really is. An IP lookup helps in two ways. It tells you where the visitor's IP address is, and it tells you whether you can trust that location, because the visitor may be connecting through a VPN, a proxy, Tor, or a privacy relay.

Picture a sports streaming service that has the rights to show a football match in Germany, Austria, and Switzerland, and nowhere else. If its check is too loose, a viewer in another country connects through a VPN server in Germany and watches the match. If it's too strict, it blocks a paying subscriber in Munich because their iPhone hides their address with iCloud Private Relay, or because their office sends all traffic through a security service in another city. The first mistake shows up when the rights holder audits you. The second shows up in your support inbox.


TL;DR

Geolocation compliance needs three answers, not two: in territory, out of territory, and unknown. First decide whether each rule comes from a contract (a licensing deal) or from a law, because that decides how strictly you treat "unknown" and what happens when the lookup fails.

  • VPN, proxy, Tor, and residential proxy addresses show the location of someone else's machine, so the visitor's location is unknown: ask them to switch the VPN off under a licensing deal, and refuse under a law.
  • Apple says iCloud Private Relay keeps the user's region, so a relay address can still tell you which region the user is in.
  • Check again when the content starts playing or a bet is placed, and whenever the visitor's IP address changes, and log every decision.

Key terms in plain English

These words come up throughout the guide:

  • Territory: the list of countries or regions where you're allowed to offer something.
  • VPN: a service that sends a visitor's traffic through its own server, so websites see the server's IP address instead of the visitor's.
  • Proxy and Tor: other ways of routing traffic through someone else's machine; Tor passes it through several volunteer-run servers.
  • Residential proxy: a proxy whose traffic comes out of a real home internet connection, so it looks like an ordinary household.
  • Privacy relay: a service such as Apple's iCloud Private Relay that hides the user's exact address but keeps their general area.
  • Corporate gateway: a security service a company sends its staff's web traffic through, which may be in another city.
  • Exit address: the IP address a website actually sees when traffic comes through a VPN, proxy, or relay.
  • Data center (hosting) address: an IP address that belongs to a server company rather than a home or mobile internet provider.
  • ASN: the number that identifies the network an IP address belongs to, shown in lookups with the network owner's name.

Every location check has three possible answers

A location check has to answer two questions. Where is this IP address? And is that where the visitor really is? It's easy to stop after the first question. But when the answer to the second one is no, the first answer stops mattering: you don't know where the visitor is.

Diagram: an IP lookup asks where the address is and whether to trust it, giving in territory, out of territory, or unknown
Every location check ends in one of three answers; anonymity decides when the answer is 'unknown'.

So every visitor lands in one of three places:

  • In territory: the address is inside the allowed area, and nothing suggests it's borrowed.
  • Out of territory: the address is outside the allowed area, and nothing suggests it's borrowed.
  • Unknown: the address belongs to a VPN, proxy, or Tor server, has no country, or the lookup didn't come back.

This three-way split is a working model, not an industry standard. A check with only two answers has to treat "unknown" as either allow or deny, and both are wrong for some of your visitors. With a separate "unknown" answer, you decide what it means for each piece of content.


The same VPN visitor might get a polite message on one page and a hard block on another. What decides it, in our recommended starting policy, is where the territory rule comes from; a contract can still demand stricter checks.

A licensing rule comes from a contract. A film studio or a sports league sells you the right to show something in a list of countries, and the contract says how carefully you have to enforce it. These rules are usually set country by country; they differ from one film or match to the next, and an occasional unknown visitor is a business risk rather than a broken law. You can ask that visitor to switch off their VPN. And for low-stakes content, such as a short news clip, you can choose to let it play if your lookup fails.

A legal rule comes from a law or a regulator, and it's stricter. US states that allow online betting, such as Ohio and Colorado, require operators to confirm a player is inside the state before accepting bets. Federal law adds a condition. The Unlawful Internet Gambling Enforcement Act allows betting within one state only if that state's law requires "age and location verification requirements reasonably designed to block access to minors and persons located out of such State" (31 U.S.C. § 5362(10)(B)). Under a rule like that, unknown means no, and a failed lookup means no as well. Blocking countries under government trade sanctions belongs in this group too; the legal notes in our geo-blocking guide cover it.

We'd decide the rule type for every film, show, match, or product before writing any code. It settles three things the rest of this guide depends on: which kinds of address you trust, what happens to unknown visitors, and what happens when the lookup itself fails.


What a VPN-aware location check returns

One request to the IPGeolocation.io IP Geolocation API with include=security returns both the location and the security data, so the "where" and the "can we trust it" questions are answered by the same lookup. These are the fields a territory check reads:

Field What It Tells You
country_code2 The country, as a two-letter code such as DE for Germany
state_code The region, as a code such as US-TX for Texas or DE-HE for Hesse; sometimes empty
is_vpn, vpn_provider_names The address is a VPN server, and which VPN when known
is_proxy, is_tor The address is a proxy server or a Tor exit
is_residential_proxy The address is a home connection carrying other people's traffic
is_relay, relay_provider_name The address is a privacy relay, such as iCloud Private Relay
is_corporate_gateway The address belongs to a company's security gateway, which isn't trying to hide anyone
is_anonymous True when any VPN, proxy, Tor, or relay signal is present
threat_score A risk score from 0 to 100; useful context, but not a territory answer

The full list of security fields is in the IP Security API field reference. Here are two real addresses we looked up on November 11, 2026, shortened to the lines that matter. The first is a VPN address from our own documentation:

{
  "ip": "2.56.188.34",
  "location": { "country_code2": "US", "state_code": "US-TX", "city": "Dallas" },
  "asn": { "as_number": "AS62240", "organization": "Clouvider Limited" },
  "security": {
    "threat_score": 80,
    "is_vpn": true,
    "vpn_confidence_score": 70,
    "is_relay": false,
    "is_anonymous": true,
    "is_cloud_provider": true
  }
}

The second is an iCloud Private Relay address. Apple publishes a list of its relay addresses with their locations, and that list places this range in Frankfurt, in the German state of Hesse:

{
  "ip": "172.225.6.1",
  "location": { "country_code2": "DE", "state_code": "DE-HE", "city": "Frankfurt", "is_eu": true },
  "asn": { "as_number": "AS36183", "organization": "Akamai Technologies, Inc." },
  "security": {
    "threat_score": 50,
    "is_vpn": false,
    "is_relay": true,
    "relay_provider_name": "Apple Relay",
    "is_anonymous": true,
    "is_cloud_provider": true
  }
}
Two IPGeolocation.io lookups: a VPN exit located in Dallas and an Apple Private Relay address that keeps Frankfurt, Germany
Both addresses are anonymized, but only the relay still tells you the user's region. Trimmed responses captured November 11, 2026.

The lines to compare are is_vpn and is_relay. Both responses also say is_anonymous: true, so a rule that only reads that one line treats them the same. But Dallas is just where the VPN company runs its server; the viewer could be anywhere. Frankfurt is the location Apple publishes for this relay range, and Apple designs Private Relay to keep each user's approximate region. Its developer documentation states that "Private Relay preserves the region the user is in", and that a website can trust the region of the address it sees (Apple, prepare your network for iCloud Private Relay). Our location for the relay matches the region Apple publishes for it.

The scores don't answer the territory question either. A vpn_confidence_score of 70 is confidence that the address is a VPN, not a 70% chance the viewer is abroad, and the relay's threat score of 50 doesn't make its region half-trustworthy. A licensing rule should look at the type of address. We've written about why a privacy relay can score 50 and still be a real customer.


How to sort each signal into a verdict

Each type of address leads to one of the three answers, and the rule type decides what you do next. The table is the starting policy we recommend; what each VPN, proxy, Tor, and relay signal means explains each flag in more depth.

Two words in the table need a quick explanation. A challenge means the content doesn't play, but the account isn't punished: the visitor sees a message asking them to switch off their VPN or proxy and try again. A location check means a stronger test of where the person is, such as the device location tools betting apps use.

What the Lookup Shows Whose Location Is It? Licensing Rule (Contract) Legal Rule (Law)
No VPN, proxy, Tor, or relay The visitor's own network Allow inside the territory, deny outside Inside the territory, the IP check is passed, but any location check the law requires still runs
Privacy relay (is_relay) The user's approximate region Treat as known; check that its precision suits your territory Treat as unknown: require a location check
Corporate gateway (is_corporate_gateway) The company's gateway, not necessarily the user's Accept the country as a working answer if your contract allows; under a region rule, unknown Treat as unknown: require a location check
VPN (is_vpn) The VPN company's server Unknown: challenge Unknown: deny
Proxy or Tor (is_proxy, is_tor) The proxy server or the Tor exit Unknown: challenge Unknown: deny
Residential proxy (is_residential_proxy) A stranger's home connection Unknown: challenge Unknown: deny
No country, or the lookup failed Nobody's Your choice for that content: deny or allow Deny
Flow from an IP lookup to the signal type and rule type, ending in allow, challenge, deny, or a location check
The same signal can need a different action under a licensing rule and a legal rule.

VPN, proxy, and Tor addresses count as unknown, not out of territory, because the server's location says nothing reliable about the visitor. Even the country a VPN or proxy service advertises for its server can be wrong. Researchers checked where 2,269 servers from seven proxy services really were. One-third were definitely not in the advertised country, and another third might not have been (Weinberg et al., "How to Catch when Proxies Lie", IMC 2018).

Residential proxies get the same treatment, even though the address belongs to a real home in a real place. That home isn't your visitor's. The guide to the difference between residential, ISP, datacenter, and mobile proxies explains why these are hard to spot from the address alone.

Relays and corporate gateways are where a blanket VPN block hurts real customers. It's also why a rule that reads only is_anonymous falls short: that flag is true for relays too. Apple suggests treating relay addresses like the shared addresses mobile carriers and large companies use, because many people share each one: block one relay address and you block many real users. For corporate gateways, our IP Security API page says to treat the location as the gateway's, not the user's own city. An employee working from France can still reach the web through a gateway in Germany, so the country is a working answer, not proof. Under a legal rule we wouldn't accept a gateway or a relay as proof of location.


When country isn't enough: region and market rules

Some territories are smaller than a country: a US state that allows betting, one region in a sports deal, a local TV market. These rules match on state_code. It uses a standard format (ISO 3166-2): the two-letter country code, a dash, then the region, such as US-NJ for New Jersey or DE-HE for Hesse. In the code later in this guide, a policy can mix country codes and region codes.

Two things change at region level. First, state_code is empty for some addresses. An empty region can't prove someone is in, say, New Jersey, so treat it as unknown instead of letting the country stand in. Second, accuracy drops as the area gets smaller. It is also lower on mobile networks (IP Geolocation API). How IP geolocation is built and how accurate each level is explains why.

Mobile networks need extra care. Phone carriers often send traffic through gateways far from the phone itself. Colorado's sports betting regulator tells operators to "Disregard IP location data for devices utilizing mobile internet (3G/4G/LTE) connections" (Colorado Division of Gaming, Bulletin 3). Under rules like Colorado's, don't let a mobile carrier's address decide a region-level check.

In the US, TV markets are often defined by Designated Market Areas (DMAs) rather than states. For those rules, adding include=dma_code to the lookup returns location.dma_code, a field the docs say is filled only for US addresses (location fields reference).


How services spot VPNs, proxies, and relays

Streaming and betting services combine several signals:

  • Known exit addresses. Detection data comes from connecting through VPN and proxy networks and recording the addresses they hand out. That's how IPGeolocation.io builds is_vpn, is_proxy, and the provider names.
  • Hosting networks. Many VPN servers run in data centers, like the Dallas address in this guide, which also shows is_cloud_provider: true. A data center address alone doesn't prove a VPN, so it supports other signals rather than deciding anything on its own.
  • Shared addresses. One address used by many accounts in many countries points to a VPN or proxy; a home connection rarely looks like that.
  • Published relay lists. Apple publishes its Private Relay addresses with their locations, so a check can recognize relay traffic and keep its region.
  • Mismatches the app can see. An app that knows the phone's time zone, or its GPS position with permission, can compare it with the IP address's country.
  • Live connection tests. A test that runs in the visitor's browser can examine the connection and estimate the visitor's country behind a VPN or proxy, with a confidence score.

For the first two in depth, read how VPN detection works.


Build the check in Python

This section is for developers. If you don't write code, skip ahead: the decision table holds the whole logic.

The walkthrough builds a small Flask service that reads the visitor's IP address, looks it up once, sorts the result into one of the three answers, applies the policy for that content, and logs the decision.

Before you start, check that you have:

  • Python 3.10 or later, with pip install flask requests.
  • An IPGeolocation.io API key with access to security data, in the IPGEO_API_KEY environment variable (API pricing shows which plans include it).
  • A setup where your app sits behind a known number of proxies, so it can read the visitor's real IP address. Reading the visitor's real IP behind a proxy or CDN covers the common setups.

The four blocks below make one file, geo_compliance.py. The first sets up the lookup fields, a policy for each piece of content, and the app:

"""Territory checks for licensed and regulated content, using IP location
plus VPN, proxy, Tor, and relay flags from the IPGeolocation.io API.

Run with: IPGEO_API_KEY=... flask --app geo_compliance run
"""

import json
import logging
import os
import time
from dataclasses import dataclass

import requests
from flask import Flask, jsonify, request
from werkzeug.middleware.proxy_fix import ProxyFix

API_URL = "https://api.ipgeolocation.io/v3/ipgeo"
API_KEY = os.environ.get("IPGEO_API_KEY")

# Security data needs a paid plan. With include=security this lookup costs
# 3 credits (1 base + 2 security); X-Credits-Charged on each response confirms it.
FIELDS = ",".join([
    "location.country_code2",
    "location.state_code",
    "security.is_vpn",
    "security.vpn_provider_names",
    "security.is_proxy",
    "security.is_residential_proxy",
    "security.is_tor",
    "security.is_relay",
    "security.relay_provider_name",
    "security.is_corporate_gateway",
])
FLAGS = ("is_vpn", "is_proxy", "is_residential_proxy", "is_tor", "is_relay", "is_corporate_gateway")

CACHE_TTL_SECONDS = 3600    # how long we reuse a lookup; the API's data is rebuilt daily
CACHE_MAX_ENTRIES = 100_000
_cache = {}

POLICY_VERSION = "2026-11-12"


@dataclass(frozen=True)
class Policy:
    territories: frozenset   # "DE" covers all of Germany; "US-NJ" covers one state
    rule: str                # "licensing" (a contract) or "regulated" (a law)
    on_lookup_error: str     # "deny" or "allow"; regulated rules always deny


# One policy per piece of content or product: where it may be offered, which
# kind of rule applies, and what to do if the lookup fails.
POLICIES = {
    "match-replay-de": Policy(frozenset({"DE", "AT", "CH"}), "licensing", "deny"),
    "news-clip": Policy(frozenset({"DE", "AT", "CH", "FR"}), "licensing", "allow"),
    # For real-money wagering the IP check is a pre-screen; the dedicated location
    # check your state requires still runs before any bet is accepted.
    "nj-wager": Policy(frozenset({"US-NJ"}), "regulated", "deny"),
}

app = Flask(__name__)
# Trust X-Forwarded-For from exactly as many proxies as you run (here, one).
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)

decision_log = logging.getLogger("geo_compliance.decisions")
logging.basicConfig(level=logging.INFO, format="%(message)s")

Each piece of content gets a Policy: where it may be offered, which kind of rule applies, and what to do when a lookup fails. match-replay-de is a football match licensed for Germany, Austria, and Switzerland, and it's blocked if the lookup fails. news-clip is a short clip that plays anyway if the lookup fails. nj-wager is a bet that falls under New Jersey's law. ProxyFix with x_for=1 trusts exactly one proxy. Set it to your real chain, counting every CDN and load balancer, make the outer proxy overwrite X-Forwarded-For, block direct access, and test with a spoofed header; otherwise visitors can fake their address.

The second block is the lookup, with a size-limited, one-hour cache:

def _prune(now):
    """Drop expired entries, then the oldest ones if the cache is still full."""
    for ip in [k for k, (ts, _) in _cache.items() if now - ts >= CACHE_TTL_SECONDS]:
        del _cache[ip]
    while len(_cache) >= CACHE_MAX_ENTRIES:
        del _cache[next(iter(_cache))]


def lookup(ip):
    """Return (data, error). error is None, "unavailable" (worth retrying),
    "invalid_request", "auth", "account", "private", "quota_or_account",
    "unexpected_status", or "bad_response"."""
    now = time.monotonic()
    cached = _cache.get(ip)
    if cached and now - cached[0] < CACHE_TTL_SECONDS:
        return cached[1], None
    if not API_KEY:
        logging.error("IPGEO_API_KEY is not set")
        return None, "auth"
    try:
        resp = requests.get(
            API_URL,
            params={"apiKey": API_KEY, "ip": ip, "include": "security", "fields": FIELDS},
            timeout=2,
        )
    except requests.RequestException as exc:
        # Log the error type only: the message can contain the URL, and the URL has the key.
        logging.warning("IP lookup failed for %s: %s", ip, type(exc).__name__)
        return None, "unavailable"
    status = resp.status_code
    if status != 200:
        logging.warning("IP lookup for %s returned HTTP %s", ip, status)
        # A timeout or server error can clear on retry. 400: invalid request;
        # 401/403: key problem; 402: account or plan problem; 423: private or
        # reserved address; 429: quota or account limit. Retrying won't fix those.
        if status in {408, 500, 502, 503, 504}:
            return None, "unavailable"
        errors = {
            400: "invalid_request",
            401: "auth", 402: "account", 403: "auth",
            423: "private", 429: "quota_or_account",
        }
        return None, errors.get(status, "unexpected_status")
    try:
        data = resp.json()
    except ValueError:
        logging.warning("IP lookup for %s returned a body that isn't JSON", ip)
        return None, "bad_response"
    if not isinstance(data, dict):
        return None, "bad_response"
    for key in ("location", "security"):
        value = data.get(key)
        if value is not None and not isinstance(value, dict):
            return None, "bad_response"
    if len(_cache) >= CACHE_MAX_ENTRIES:
        _prune(now)
    _cache[ip] = (now, data)
    return data, None

Failures return a category instead of crashing: a timeout or a temporary server error (HTTP 408 or 5xx) is worth retrying, while an invalid request (400), a bad key (401), a plan problem (402), or a quota or account limit (429) needs a person. A response that isn't a JSON object, or whose location or security isn't an object, counts as a bad response and isn't cached. Error messages are logged by type only, because request URLs carry the key. In local testing you'll see HTTP 423, which the API returns for private and reserved addresses such as 127.0.0.1. IPv6 addresses work the same way as IPv4.

The third block turns a lookup into an answer:

def classify(data):
    """Reduce a lookup to (signal, country, region)."""
    loc = data.get("location") or {}
    sec = data.get("security")
    country = loc.get("country_code2") or None
    region = loc.get("state_code") or None
    if not isinstance(sec, dict) or any(not isinstance(sec.get(f), bool) for f in FLAGS):
        return "no_security_data", country, region   # missing or malformed flags never mean "clean"
    # Anonymizers win over every other flag: a VPN that is also a relay is a VPN.
    if sec["is_vpn"] or sec["is_proxy"] or sec["is_tor"] or sec["is_residential_proxy"]:
        signal = "anonymizer"   # the location is the exit server's, not the viewer's
    elif sec["is_relay"]:
        signal = "relay"        # iCloud Private Relay and similar keep the user's region
    elif sec["is_corporate_gateway"]:
        signal = "gateway"      # location is the gateway's, not the user's own city
    else:
        signal = "direct"
    return signal, country, region


def in_territory(policy, country, region):
    """True or False, or None when the answer depends on a region we don't have."""
    if country in policy.territories:
        return True             # a country code covers every region in that country
    if region is not None:
        return region in policy.territories
    # A region rule for this country ("US-NJ") can't be settled without a region.
    if any(code.startswith(f"{country}-") for code in policy.territories):
        return None
    return False


def decide(policy, data, error=None):
    """Return (verdict, action, reason) for one request.

    Actions: allow, challenge (ask to switch off the VPN), deny, location_check
    (hand over to a stronger location check), or unavailable (verification failed).
    """
    regulated = policy.rule == "regulated"
    fail = "unavailable" if regulated or policy.on_lookup_error == "deny" else "allow"
    if data is None:
        return "unknown", fail, f"lookup_{error or 'failed'}"

    signal, country, region = classify(data)
    if signal == "no_security_data" or country is None:
        return "unknown", fail, signal if country else "no_location"

    if signal == "anonymizer":
        if regulated:
            return "unknown", "deny", "anonymizer_blocked"
        return "unknown", "challenge", "anonymizer_location_unverified"
    if regulated and signal in ("relay", "gateway"):
        return "unknown", "location_check", f"{signal}_needs_location_check"

    if signal == "gateway":
        region = None   # a gateway's location only counts at country level
    match = in_territory(policy, country, region)
    if match is None:
        if regulated:
            return "unknown", "location_check", "region_unknown"
        return "unknown", "challenge", "region_unknown"
    if not match:
        return "out_of_territory", "deny", signal
    if regulated:
        # Passing here only clears the IP pre-screen; the stronger location check decides.
        return "in_territory", "location_check", "prescreen_pass"
    return "in_territory", "allow", signal

classify checks for VPNs, proxies, and Tor first, so an address flagged as both a VPN and a relay counts as a VPN; that order is a policy choice. A missing or malformed security flag counts as a failed lookup, never as clean. decide is the decision table in code:

  • VPN, proxy, Tor, and residential proxy addresses are unknown: a challenge under licensing, a denial under a legal rule.
  • Licensing rules trust relays and corporate gateways (gateways by country only).
  • Legal rules send relays, corporate gateways, and empty regions to the stronger location check (location_check) instead of deciding.
  • Under a legal rule, a visitor inside the territory is never simply allowed: the answer is location_check with the reason prescreen_pass, so the log never claims the IP check alone approved a bet.

The last block is the web route that ties it together and writes the decision log:

@app.route("/access/<content_id>")
def access(content_id):
    policy = POLICIES.get(content_id)
    if policy is None:
        return jsonify(error="unknown content"), 404

    ip = request.remote_addr
    data, error = lookup(ip)
    verdict, action, reason = decide(policy, data, error)
    sec = (data or {}).get("security") or {}

    # A record of what the system decided and why, kept only as long as contracts
    # and regulators require and readable only by the people who need it.
    decision_log.info(json.dumps({
        "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "policy_version": POLICY_VERSION,
        "content": content_id,
        "rule": policy.rule,
        "ip": ip,
        "country": ((data or {}).get("location") or {}).get("country_code2"),
        "region": ((data or {}).get("location") or {}).get("state_code"),
        "flags": [f for f in FLAGS if sec.get(f)],
        "verdict": verdict,
        "action": action,
        "reason": reason,
    }))

    if action == "allow":
        return jsonify(content=content_id, allowed=True)
    if action == "location_check":
        return jsonify(content=content_id, allowed=False, next_step="location_check", reason=reason)
    if action == "unavailable":
        # The region is unconfirmed, not out of territory. Only a temporary
        # outage is worth retrying; a key, plan, or credits problem needs a person.
        if reason == "lookup_unavailable":
            message, headers = "We couldn't confirm your region just now. Try again in a moment.", {"Retry-After": "30"}
        else:
            message, headers = "Region checks are unavailable right now. We're working on it.", {}
        return jsonify(content=content_id, allowed=False, reason=reason, message=message), 503, headers
    if reason == "anonymizer_blocked":
        message = "We can't confirm your location while a VPN or proxy is on. Turn it off and try again."
    elif reason == "anonymizer_location_unverified":
        message = "This content is licensed for specific regions. Turn off your VPN or proxy and try again."
    elif reason == "region_unknown":
        message = "We couldn't confirm your region from this connection."
    else:
        message = "This content isn't available in your region."
    return jsonify(content=content_id, allowed=False, reason=reason, message=message), 403

Refusals and challenges return HTTP 403 (forbidden) with a reason code your app can turn into the right message. HTTP 451 exists for content blocked for legal reasons; use it only where your lawyers agree that applies. A failed lookup returns 503 (service unavailable); only a temporary outage tells the visitor to retry.

To try it, use Flask's test client and pass the address in X-Forwarded-For, a shortcut that only works in tests:

from geo_compliance import app

client = app.test_client()
for ip in ("2.56.188.34", "172.225.6.1"):
    resp = client.get("/access/match-replay-de", headers={"X-Forwarded-For": ip})
    print(ip, resp.status_code, resp.get_json())

With the two lookups shown earlier, the VPN visitor gets the "switch off your VPN" message and the relay visitor is allowed:

2.56.188.34 403 {'allowed': False, 'content': 'match-replay-de', 'message': 'This content is licensed for specific regions. Turn off your VPN or proxy and try again.', 'reason': 'anonymizer_location_unverified'}
172.225.6.1 200 {'allowed': True, 'content': 'match-replay-de'}

Requesting /access/nj-wager from the relay address returns next_step: location_check with the reason relay_needs_location_check, because a legal rule doesn't accept a relay as proof of location. To enforce the same rules at your CDN (the network that delivers your content), firewall, or web server instead, see how to geo-block visitors by country at the CDN, WAF, or application.

The sample leaves out three things on purpose:

  • A shared cache. With several workers or threads, use Redis with a TTL, and pause lookups briefly after repeated 429s or outages.
  • The mid-session check. Store the address you last checked with the visitor's session, and call decide again when a request comes from a different one.
  • EU subscribers abroad. is_eu only says the IP address is in the EU. Portability needs the subscriber's verified home country, stored with their account, checked before the territory rule.

When to check again

A check at sign-in only tells you where the visitor was when they signed in. Content plays and bets happen later, so check again at the moments that count:

Session timeline with location checks at sign-in, at playback or each wager, on an IP change, and in long sessions
Check where it counts: before content plays or a bet is placed, and again when the address changes.
  • When content starts playing, or before each bet. This is the moment a rights holder or regulator cares about, and the moment your log should record.
  • When the IP address changes mid-session. Colorado's bulletin asks for "A geolocation check immediately upon a change of IP address mid-session". The same logic suits streaming: a new address is a new claim about where the visitor is.
  • During long sessions. An address can be reclassified, say as a residential proxy, after the session started. The one-hour cache limits how long you reuse an old answer; how often to recheck an active session is a risk decision.

Browsing a catalogue usually doesn't need its own check. Show what's licensed for the visitor's apparent location, and enforce the rule when something starts playing.

Paid streaming services in the EU follow different timing for their subscribers: they confirm the subscriber's home country when the contract starts and renews, as the EU portability section explains.


Log every decision as evidence

When a rights holder asks why a match played in a country it shouldn't have, or a regulator asks how you kept out-of-state players away, your answer is the decision log. Each record should hold:

  • The time and the policy version, so you can show which rule applied that day.
  • The content or product, and its rule type.
  • The inputs: country, region, and the security flags the decision used.
  • The answer and the action: in territory, out of territory, or unknown, and allow, challenge, or deny, with the reason code.

The access route writes exactly that, as one line of JSON per request. The log shows what your system decided, not that the decision was legally sufficient. It's also personal data: limit who can read it, encrypt it, keep it only as long as your contracts and regulators require, and consider shortening or pseudonymizing stored IP addresses. Keep EU portability checks out of this log. Data from their IP address check "shall be collected in binary format only": inside or outside the subscriber's home country, with no address or location kept, and it must be destroyed once each check is complete (Regulation (EU) 2017/1128, consolidated text).


The EU and US rules that change the answer

Territory rules aren't only private contracts, and a few laws change what a check is allowed to do. This is a plain-language summary for engineers, not legal advice, and the examples don't establish compliance with any contract or jurisdiction; ask a lawyer.


1. EU portability: Regulation (EU) 2017/1128

Since April 1, 2018, a paid online content service in the EU must let a subscriber who is temporarily in another EU country "access and use the online content service in the same manner as in the Member State of residence", with the same content. In practice: a German subscriber on holiday in Spain gets the German catalogue. Providers confirm which country the subscriber lives in using no more than two methods from a list in Article 5, and an IP address check is one of them. At sign-up and renewal, an IP check must be combined with another method from the list. During the contract, if the provider has reasonable doubts, it can be used alone. For a streaming check, this means an IP address in another EU country tells you the subscriber is temporarily abroad, not out of territory. The Regulation doesn't mention VPNs at all, so it neither requires nor forbids blocking them. What it forbids is denying subscribers their home catalogue because they crossed an EU border.


2. EU geo-blocking: Regulation (EU) 2018/302

The Geo-blocking Regulation limits unfair treatment of customers based on their nationality or where they live inside the EU. But the European Commission's 2020 review states that "Audiovisual services are fully excluded from the scope of the Regulation" (COM(2020) 766), so film and TV streaming isn't covered. Other copyright-based services, such as e-books, music, software, and games, are covered, except for Article 4, the rule against offering different terms to customers from different EU countries (Regulation (EU) 2018/302). So an e-book or music store may still sell differently by country, but should have any blocking checked against the rest of the Regulation.


3. EU sports rights

In 2011 the EU's Court of Justice ruled that a licensing system which "prohibits television viewers from watching the broadcasts with a decoder card in other Member States is contrary to EU law". The same ruling confirmed that giving one broadcaster the exclusive right to show matches in a territory isn't banned in principle (CJEU press release No 102/11). For your check, that means exclusive sports deals are allowed, but a deal that asks you to stop viewers in one EU country from using access bought in another is worth a legal review.


4. US online betting

The federal rule on betting within one state depends on state law requiring location checks, as quoted in the section on rule types. Each state sets its own details, so treat the code as illustrative and adapt it to your state and approved location provider. In Ohio, a player whom the location-checking provider finds outside the state "must be blocked from placing wagers" (Ohio Adm. Code 3775-17-01). Colorado's bulletin tells operators to "Detect and block location data fraud (e.g. Proxy, Fake Location Apps, Virtual Machines, Remote Desktop Programs, etc.)" and to use IP and proxy databases "updated daily at a minimum".


Where IP data stops

An IP lookup with security data fits licensing territories well, and works as a fast first check on every request. It isn't the whole answer for US real-money betting, where state rules call for dedicated location technology. For betting, run the IP check first to stop obvious VPN and out-of-state traffic quickly, then let the dedicated location check make the final call.

For websites and web players there's a step in between. IPGeolocation.io's Real-Time Proxy & VPN Detection runs a short test in the visitor's browser and estimates the country behind the VPN or proxy (the visitor_actual_location.actual_country_code field), with a confidence score. The Real-Time Proxy & VPN Detection documentation recommends checking that confidence before acting. It only runs in a browser, so mobile apps and backend jobs use the IP lookup.

When your check gets it wrong, give people a way out. A denial page that explains the reason and links to report a wrong IP location lets a wrongly blocked visitor get their address corrected.


Geolocation compliance data from IPGeolocation.io

IPGeolocation.io gives a territory check everything it needs in one call. That means geolocation down to region and city, and security data that names VPN, proxy, residential proxy, and Tor exits, with provider names and a 0 to 100 threat score. ASN, company, abuse contact, time zone, and user agent data are available from the same API when your other systems need them. The difference this guide depends on is built into the data: relays and corporate gateways have their own flags, so you can keep Private Relay users and office workers while holding a firm line on VPNs.

The location data is accurate at the country and region levels territory rules depend on, and we check it by measuring the network directly (with ping, traceroute, and BGP routing data) rather than relying on registry records alone (how we measure accuracy). Security data is collected continuously and published in a full daily update.

You can run the same checks wherever you enforce them:

Start with the Proxy & VPN Detection API and run your first VPN-aware lookup.

Frequently asked questions

Geolocation compliance is the practice of offering content, bets, or services only in the places a licensing contract or a law allows, based on the visitor's location. IP geolocation compliance combines the IP address's country and region with VPN, proxy, Tor, and relay signals that show whether that location really belongs to the visitor.

Streaming services typically match the viewer's IP address against known VPN and proxy addresses, then add supporting signals: data center networks, many accounts on one address, and mismatches with the device's time zone or GPS. Tests that run in the browser can also estimate the viewer's country behind the VPN.

A VPN can bypass a check that only reads the IP address's country because the service sees the VPN server's location. A check that also reads VPN, proxy, and Tor flags treats that location as unknown instead, and a licensing rule can then ask the viewer to switch off the VPN before the content plays.

When a visitor uses a VPN, IP geolocation shows the VPN server's location, which can be anywhere relative to the visitor. Even the server's advertised country can be wrong: researchers who measured 2,269 proxy servers found one-third definitely outside the countries their services advertised. That's why a VPN flag should make the location unknown.

Usually not. Apple states that Private Relay preserves the region the user is in, and IPGeolocation.io flags relay addresses with is_relay and the provider name, separately from VPNs. A content licensing rule can accept a relay's region; a legal rule, such as a betting check, should still require a dedicated location check.

Not directly. Regulation (EU) 2017/1128 doesn't mention VPNs. It requires paid content services to give subscribers who are temporarily in another EU country the same content as at home, so a check must not deny an EU subscriber their home catalogue just because their IP address is in another EU country.

No. The IPGeolocation.io free plan includes 1,000 API credits per day for core location data, including country and region codes, but security fields such as is_vpn and is_relay need a paid plan. Paid plans start at $19 per month for 150,000 credits, and a lookup with security data costs 3 credits.

Related Guides

What Is RDAP? The Protocol Replacing WHOIS for IP Data
What Is RDAP? The Protocol Replacing WHOIS for IP Data

RDAP is the successor to WHOIS for IP address and ASN registration data. Follow one real lookup from IANA's bootstrap data to a registry record, see what changes from WHOIS, and learn which conclusions the record supports.

Posted on December 2, 2026
Read More: What Is RDAP? The Protocol Replacing WHOIS for IP Data
IP Data for Advertising and Marketing, From Bid to Report
IP Data for Advertising and Marketing, From Bid to Report

What an ad stack can learn from the IP address on each request, from the bid to the report: how precise each location level is, which addresses to keep out of audiences and reports, and which consent rules apply.

Posted on December 1, 2026
Read More: IP Data for Advertising and Marketing, From Bid to Report
IPv4 vs IPv6: The Key Differences and What They Change
IPv4 vs IPv6: The Key Differences and What They Change

IPv4 addresses are 32 bits long and IPv6 addresses are 128 bits. See every other difference in one table, which IPv6 myths to drop, and what changes when your code, logs, and rate limits meet IPv6 traffic.

Posted on November 29, 2026
Read More: IPv4 vs IPv6: The Key Differences and What They Change
When Should You Use Real-Time Proxy & VPN Detection vs IP Reputation?
When Should You Use Real-Time Proxy & VPN Detection vs IP Reputation?

An IP reputation lookup tells you what an address has done; Real-Time Proxy & VPN Detection tells you whether this session is anonymized right now. Which check to run at each step, from signup to payouts, and what to do when the two disagree.

Posted on November 29, 2026
Read More: When Should You Use Real-Time Proxy & VPN Detection vs IP Reputation?
Residential vs Business IP Addresses: How to Tell Them Apart
Residential vs Business IP Addresses: How to Tell Them Apart

A website can't see your internet plan, only who an IP address is registered to and which network carries it. Here's how company type, ASN type, and proxy flags tell home, office, and server traffic apart, and where they mislead.

Posted on November 28, 2026
Read More: Residential vs Business IP Addresses: How to Tell Them Apart
Public vs Private IP Addresses: Differences and Ranges
Public vs Private IP Addresses: Differences and Ranges

Private IP addresses come from three ranges: 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. See how they differ from public addresses, why 100.64.0.0/10 isn't private, and how to check any IP by eye, in code, or with a lookup.

Posted on November 28, 2026
Read More: Public vs Private IP Addresses: Differences and Ranges

Subscribe to Our Newsletter

Get the latest in geolocation tech, straight to your inbox.