How to Block VPN, Proxy & TOR Traffic Using IP? A Technical Guide

Maintaining the integrity of a web application requires knowing who is on the other side of a connection. While privacy tools like VPNs, proxies, and the TOR network have legitimate use cases, they are frequently leveraged by malicious actors to bypass geo-fencing, conduct credential stuffing attacks, or commit payment fraud.

For backend engineers, identifying this "anonymized" traffic is the first step toward building a robust security posture. This guide explores the technical mechanisms behind IP intelligence and how to implement effective blocking strategies.

Blocking tor vpn and proxy traffic using ip intelligence

Understanding Anonymous Traffic Types

Before implementing a blocklist, it is essential to distinguish between the different methods users use to hide their identity:

How Detection Works Internally

IP intelligence providers maintain massive, frequently updated databases that categorize IP addresses based on several signals:

  1. ASN Analysis: By examining the Autonomous System Number (ASN), a provider can determine if an IP belongs to a residential ISP (e.g., Comcast) or a hosting provider (e.g., Linode). Most consumer traffic should originate from residential or mobile ASNs. Check ARIN documentation on understanding ASN and IP allocation.

  2. Infrastructure Probing: Active scanning of IP ranges to find open ports commonly used by proxy protocols (SOCKS5, HTTP CONNECT) or VPN protocols (OpenVPN, WireGuard).

  3. BGP Feed Monitoring: Analyzing Border Gateway Protocol (BGP) announcements to identify new IP ranges acquired by known VPN companies.

  4. TOR Consensus Files: The TOR project publishes a public list of active exit nodes. Intelligence APIs ingest these lists in real-time to provide up-to-the-minute accuracy.

Technical Implementation

Implementing a blocklist involves querying an IP intelligence API during the request lifecycle—typically at the middleware or load balancer level—and deciding whether to proceed based on the returned metadata.

The API Request

To check an IP address, you send a GET request to the intelligence endpoint. For example, using curl:

curl -X GET "https://api.ip2geoapi.com/ip/1.2.3.4?key=YOUR_API_KEY"

The JSON Response

A comprehensive API returns a structured response that includes a security or proxy object. This is the data you will use to drive your logic.

{
  "success": true,
  "ip": "8.8.8.8",
  "version": "ipv4",
  "geo": {
    "city": "Chicago",
    "country": "United States",
    "countryCode": "US",
    .
     ..other geo data
  },
  "security": {
    "isHosting": true,
    "isProxy": false,
    "proxyType": null,
    "isVpn": false,
    "vpnProvider": null,
    "vpnProviderUrl": null,
    "isTor": false,
    "isAnonymous": true,
    "trustScore": 65,
    "riskLevel": "medium"
  }
}

Implementing an IP intelligence check on every request can introduce unnecessary latency. Below are production-ready examples for Python and Node.js that use Redis to cache API responses.

Python Implementation (Flask + Redis)

This example uses redis-py and requests. We cache the security data for 24 hours to minimize external API overhead.

import redis
import requests
import json
from flask import Flask, request, jsonify

app = Flask(__name__)

# Configure Redis and API Key
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
API_KEY = "YOUR_API_KEY"
CACHE_TTL = 86400  # 24 hours

def get_ip_intelligence(ip):
    # Check cache first
    cached_data = r.get(f"ip_auth:{ip}")
    if cached_data:
        return json.loads(cached_data)

    # Cache miss - call API
    url = f"https://api.ip2geoapi.com/ip/{ip}?key={API_KEY}"
    try:
        response = requests.get(url, timeout=2)
        if response.status_code == 200:
            data = response.json()
            # Store in Redis with expiration
            r.setex(f"ip_auth:{ip}", CACHE_TTL, json.dumps(data))
            return data
    except requests.RequestException:
        return None
    return None

@app.before_request
def security_filter():
    client_ip = request.remote_addr
    intel = get_ip_intelligence(client_ip)
    
    if intel and intel.get("security"):
        sec = intel["security"]
        # Block if it's a VPN, Proxy, or TOR exit node
        if sec.get("is_vpn") or sec.get("is_proxy") or sec.get("is_tor"):
            return jsonify({"error": "Access denied: Anonymous traffic prohibited"}), 403

@app.route("/api/data")
def protected_endpoint():
    return jsonify({"message": "Welcome, verified user!"})

if __name__ == "__main__":
    app.run()

Node.js Implementation (Express + Redis)

This implementation uses the modern redis (v4+) client and axios.

const express = require('express');
const redis = require('redis');
const axios = require('axios');

const app = express();
const API_KEY = 'YOUR_API_KEY';
const CACHE_TTL = 86400; // 24 hours

const redisClient = redis.createClient();
redisClient.connect().catch(console.error);

async function getIpIntel(ip) {
    const cacheKey = `ip_intel:${ip}`;
    
    // Check Redis cache
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) return JSON.parse(cachedData);

    // Call ip2geoapi.com
    try {
        const response = await axios.get(`https://api.ip2geoapi.com/ip/${ip}?key=${API_KEY}`, { timeout: 2000 });
        const data = response.data;
        
        // Save to cache
        await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(data));
        return data;
    } catch (err) {
        console.error('IP Intel API Error:', err.message);
        return null;
    }
}

// Middleware to block anonymous traffic
app.use(async (req, res, next) => {
    const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    const intel = await getIpIntel(ip);

    if (intel && intel.security) {
        const { is_vpn, is_proxy, is_tor } = intel.security;
        if (is_vpn || is_proxy || is_tor) {
            return res.status(403).json({ error: 'Anonymous connections are blocked.' });
        }
    }
    next();
});

app.get('/api/resource', (req, res) => {
    res.json({ status: 'Success', data: 'Protected data accessed.' });
});

app.listen(3000, () => console.log('Security Gateway running on port 3000'));

Key Takeaways for Developers

VPN vs Proxy vs TOR: Practical Differences

Type Typical Source Use Case Detection Confidence
VPN Commercial providers Privacy, geo-bypass Medium–High
Proxy Datacenters or residential Scraping, automation Medium
TOR TOR exit nodes Strong anonymity Very High

TOR traffic is usually the easiest to detect and block. VPN and proxy detection requires more nuance due to legitimate usage.

If you want to soften the blocking strategy, follow this:

if isTor:
    block_request()

if isVpn or isProxy:
    require_additional_verification()

This approach avoids overly aggressive blocking while still reducing abuse.

Recommended Strategy:

Use Cases for Blocking Anonymous IPs

Why Choose ip2geoapi.com?

For developers looking for a reliable, high-performance solution, ip2geoapi.com provides a best-in-class IP intelligence engine. It is designed specifically for high-throughput backend environments where latency is a critical factor.

You can get your free API key here and start securing your traffic in minutes.

Common Pitfalls and Edge Cases

1. False Positives with Corporate VPNs

Not all VPNs are malicious. Many enterprise users are required to use corporate VPNs for security. If your SaaS target audience is B2B, a blanket "Block All VPN" policy might lock out your primary users. In these cases, it is better to flag the account for manual review rather than hard-blocking.

2. IPv6 Density

Detecting proxies in IPv6 is more complex than IPv4 due to the sheer size of the address space ($2^{128}$). Ensure your provider doesn't just block individual IPs but can identify entire /64 or /48 blocks that belong to hosting providers.

3. Latency Overhead

Making a blocking decision on every single request can add latency.Optimization Tip: Cache the results of the IP lookup in a fast in-memory store like Redis for a short TTL (e.g., 1–6 hours) to avoid redundant API calls.

Conclusion

Blocking VPN, Proxy, and TOR traffic is a balancing act between security and user experience. By integrating a high-fidelity intelligence API like ip2geoapi.com, you gain the visibility needed to make informed decisions—allowing legitimate users through while stopping automated threats at the door.

Ready to secure your backend? Sign up at ip2geoapi.com to claim your 100,000 free monthly requests and start implementing your IP-based security rules today.

Vijay Prajapati
About the Author

Vijay Prajapati

I am a backend developer and founder of IP2GeoAPI, specializing in IP geolocation, network intelligence, and API architecture. I focus on building fast, accurate and scalable APIs for developers.

Connect on LinkedIn

Ready to Integrate?

Start using our IP geolocation & intelligence API in minutes. Sign up now and get your FREE API key with 100,000 monthly quota every month — no credit card required.

Join developers worldwide who rely on IP2GeoAPI for speed, accuracy, and reliability.