How can I use an API to detect if an IP address is a VPN in Python?

To detect if an IP address is a VPN using IP2Location.io in Python, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed Python and we won't cover that here. You will also need a paid subscription to the Security plan. Subscribe now!
  2. In the command line, run the command below to install the Requests package using pip if you don't have it installed.
    Bash
    
    python -m pip install requests
    			
  3. Save the below code into a file called test.py on your computer.
    Python
    
    import requests
    from requests.exceptions import HTTPError
    import json
    
    key = 'YOUR_API_KEY'
    ip = '8.8.8.8'
    payload = {'key': key, 'ip': ip, 'format': 'json'}
    
    try:
        response = requests.get('https://api.ip2location.io/', params=payload)
        response.raise_for_status()
    except HTTPError as http_err:
        if 'error_message' in response.text:
            myobj = json.loads(response.text)
            print(f"ERROR: {myobj['error']['error_message']}")
        else:
            print(f"ERROR: {http_err}")
    except Exception as err:
            print(f"ERROR: {err}")
    else:
        try:
            myobj = json.loads(response.text)
            if 'proxy' in myobj:
                if myobj['proxy']['is_vpn'] is True:
                    print(f"The IP {ip} is a VPN.")
                else:
                    print(f"The IP {ip} is NOT a VPN.")
            else:
                print("ERROR: The is_vpn field requires a paid subscription to the Security plan.")
        except json.JSONDecodeError as e:
            print("ERROR: Invalid JSON in response.")
    			
  4. In the command line, run the below command.
    Bash
    
    python test.py
    			

This script will check if the specified IP address is a VPN. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free