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.

Understanding Anonymous Traffic Types
Before implementing a blocklist, it is essential to distinguish between the different methods users use to hide their identity:
- VPN (Virtual Private Network): Encrypts traffic and tunnels it through a remote server. The destination server sees the IP of the VPN provider rather than the user’s residential IP.
- Proxies: Intermediary servers that forward requests. These range from transparent proxies (which reveal the original IP) to elite/anonymous proxies (which strip all identifying headers).
- TOR (The Onion Router): A decentralized network that bounces traffic through multiple nodes. The "Exit Node" is the final hop where the traffic re-enters the public internet.
- Datacenter IPs: Often utilized by automated bots and scrapers. These IPs belong to cloud providers like AWS, GCP, or DigitalOcean rather than consumer ISPs.
How Detection Works Internally
IP intelligence providers maintain massive, frequently updated databases that categorize IP addresses based on several signals:
-
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.
-
Infrastructure Probing: Active scanning of IP ranges to find open ports commonly used by proxy protocols (SOCKS5, HTTP CONNECT) or VPN protocols (OpenVPN, WireGuard).
-
BGP Feed Monitoring: Analyzing Border Gateway Protocol (BGP) announcements to identify new IP ranges acquired by known VPN companies.
-
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
- Failure Mode: Notice the try/except blocks. If the API or Redis is down, it is usually safer to fail open (allow the request) to avoid locking out legitimate users due to a system failure.
- Header Trust: When behind a load balancer (like Nginx or AWS ALB), ensure you are pulling the IP from X-Forwarded-For or CF-Connecting-IP, but only if you trust the proxy.
- Efficiency: Using setex (Redis) ensures your memory doesn't fill up with stale IP data, automatically purging old entries after 24 hours.
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:
- Hard-block TOR for sensitive endpoints
- Soft-block VPN/proxy (CAPTCHA, email verification, rate limits, fake signups)
- Log decisions for auditing and tuning
Use Cases for Blocking Anonymous IPs
- Fraud Prevention: High-risk actions like credit card processing or account registration should often be restricted to non-proxy residential IPs to prevent mass-scale bot attacks.
- Compliance and Licensing: If your content is licensed only for the UK, allowing a user to bypass this via a US-based VPN puts you in breach of contract.
- DDoS Mitigation: Large-scale Layer 7 attacks often originate from compromised proxies or TOR exit nodes. Identifying these at the edge can save significant compute resources.
- Blocking traffic based on country: You can deny access from some of the high risk countries.
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.
- Exceptional Accuracy: Our database is updated daily, ensuring that new VPN ranges and TOR exit nodes are identified within hours of appearing.
- IPv4 and IPv6 Support: As the internet transitions, our API handles both protocols seamlessly, providing consistent security metadata across the board.
- Developer-First Pricing: We believe in supporting the developer community. We offer a generous free tier of 100,000 requests per month, allowing you to protect your applications without immediate overhead.
- Sub-millisecond Latency: Our infrastructure is globally distributed to ensure your API calls don't become a bottleneck in your request pipeline.
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.