An IP in your logs is a VPN or proxy when strangers' traffic leaves the internet through it. A geolocation lookup won't tell you that. A VPN server in Frankfurt geolocates to Frankfurt, exactly like the bakery next door, and a residential proxy exit is somebody's real home connection.
This article builds a small .NET 8 console tool that reads an access log, keeps the public client addresses, checks them in bulk, and writes a CSV that labels each one: VPN, proxy, Tor exit, privacy relay, corporate gateway, hosting, or a plain home line. It ends with the part most tutorials skip, which is deciding what not to block.
TL;DR
Geolocation data answers "where is this IP". VPN and proxy detection answers "what kind of connection is this", and that needs data collected by watching exits, not mapping ranges.
Four signals help: who owns the network, public lists (Tor exits, Apple Private Relay egress, cloud ranges), a time zone that doesn't match, and impossible travel between logins.
The C# tool counts requests per IP, drops private and reserved addresses, and sends 1,000 addresses per request to a bulk security endpoint.
In a sample run, a Tor exit scored 95, a residential proxy 90, and two Apple Private Relay addresses 50 each.
Sort by the threat score, decide on the flags. Relays, company gateways, and mobile carriers put many real people behind one address.
If you only remember one thing: the threat score is a sort key, not a verdict. The flags tell you why an address scored what it did, and that's what your rules should read.
Why a geolocation lookup can't spot a VPN or proxy
A geolocation database maps address ranges to a country, a city, and the network that owns them. That data comes from registries, routing tables, and measurement, and it describes the address. It doesn't describe who is using it right now.
That gap is the whole problem. A commercial VPN rents servers in a data center, and those servers geolocate, correctly, to the data center. A residential proxy network routes traffic through real home and mobile connections, so the owner field shows an ordinary consumer ISP. Neither the location nor the ISP changes when an address starts carrying other people's traffic.
What does change is behavior. The address appears in a VPN app's server list, gets handed out by a proxy network, or shows up in the Tor network's list of exits. Detection data is collected by watching for exactly that: connecting to VPN services and recording the exit addresses, sampling proxy pools, and reading the Tor consensus. You can do a little of this yourself, and the next section shows how far that gets you.
The four signals you can check
Who owns the network
Most VPN exits live on hosting networks, so an address owned by a hosting provider is worth a second look. A human logging in from a Scaleway or OVH server is unusual; a scraper doing it is routine.
Ownership alone misleads, though. Apple's iCloud Private Relay hands traffic to the internet through partners such as Akamai and Cloudflare, so a Safari user with Private Relay turned on arrives from a CDN's address space. In the sample run below, 172.225.32.1 is an Apple relay on Akamai's network and 104.28.47.1 is one on Cloudflare's. Companies that route staff through a secure web gateway look the same: every employee arrives from the security vendor's cloud. Treat "hosting" as a reason to look closer, never as "this is a VPN".
Public lists
Three lists are free and worth wiring in:
The Tor Project publishes a bulk exit list, refreshed at most every 40 minutes.
Apple publishes the iCloud Private Relay egress ranges as a CSV.
AWS, Google Cloud, and Microsoft Azure publish their address ranges as JSON files.
Notice what's missing. There's no official list of commercial VPN exits, and residential proxy networks never publish theirs, because their customers pay for not being on a list. That gap is where commercial IP security data earns its keep, and it's why the tool below uses a lookup service instead of only these files.
A time zone that doesn't match
A browser reports its time zone through the Intl API, and an IP lookup returns the time zone of the address. A browser set to Asia/Karachi on an address in America/Chicago is a classic VPN tell. Your access log doesn't record the browser's time zone, though, so this signal needs a line of JavaScript at login and a column in your auth table. Travelers and people who never changed their laptop clock trip it too, which makes it a weight, not a verdict.
Impossible travel
The same account logs in from Lahore and, forty minutes later, from Toronto. Nobody flies that fast, so one of the two sessions is probably on a VPN or proxy (or the account is shared, or stolen). This one needs a user ID on every log line. It also fires every time someone toggles a VPN, which is half the point.
The first two signals can come straight out of a log file. The last two need application data. The tool below handles the first two in one pass.
Build the log checker in C
The examples call the bulk endpoint of the ipgeolocation.io IP Security API, which takes a JSON array of addresses and returns VPN, proxy, Tor, relay, bot, and hosting flags for each one. VPN and proxy data isn't part of most free IP lookup tiers, so check that your key can read security data before you point this at a month of logs.
The project needs nothing outside the base class library:
dotnet new console -n LogVpnCheck -f net8.0
cd LogVpnCheck
export IPGEO_API_KEY="your-key"
Keep the key in an environment variable (or user secrets in development). The endpoint takes it as a query parameter, which matters for logging later.
Step 1: read the log and keep public addresses
LogReader.cs pulls the first field from each line, which is the client address in the common and combined log formats, and counts requests per address.
using System.Net;
using System.Text.RegularExpressions;
namespace LogVpnCheck;
public static partial class LogReader
{
// Addresses that can't be a real visitor and that the lookup would reject anyway:
// private, loopback, link-local, carrier-grade NAT, documentation, multicast, reserved.
private static readonly IPNetwork[] NonPublic =
[
IPNetwork.Parse("0.0.0.0/8"), IPNetwork.Parse("10.0.0.0/8"),
IPNetwork.Parse("100.64.0.0/10"), IPNetwork.Parse("127.0.0.0/8"),
IPNetwork.Parse("169.254.0.0/16"), IPNetwork.Parse("172.16.0.0/12"),
IPNetwork.Parse("192.0.0.0/24"), IPNetwork.Parse("192.0.2.0/24"),
IPNetwork.Parse("192.168.0.0/16"), IPNetwork.Parse("198.18.0.0/15"),
IPNetwork.Parse("198.51.100.0/24"), IPNetwork.Parse("203.0.113.0/24"),
IPNetwork.Parse("224.0.0.0/4"), IPNetwork.Parse("240.0.0.0/4"),
IPNetwork.Parse("::/127"), IPNetwork.Parse("100::/64"),
IPNetwork.Parse("2001:db8::/32"), IPNetwork.Parse("fc00::/7"),
IPNetwork.Parse("fe80::/10"), IPNetwork.Parse("ff00::/8"),
];
[GeneratedRegex(@"^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$")]
private static partial Regex DottedQuad();
// Counts requests per client IP. Common and combined log formats start with the
// client address; behind a CDN, make sure that field holds the visitor, not the CDN.
public static Dictionary<string, int> CountClientIps(IEnumerable<string> lines)
{
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var line in lines)
{
var end = line.IndexOf(' ');
var ip = Normalize(end > 0 ? line[..end] : line);
if (ip is null) continue;
counts[ip] = counts.GetValueOrDefault(ip) + 1;
}
return counts;
}
// Returns the canonical text of a public IP, or null for anything else.
public static string? Normalize(string token)
{
// IPAddress.TryParse also accepts legacy forms ("8.8" becomes 8.0.0.8,
// "134744072" becomes 8.8.8.8), so only strict dotted quads or IPv6 text get in.
if (!DottedQuad().IsMatch(token) && !token.Contains(':')) return null;
if (token.Contains('%')) return null; // zone IDs only appear on link-local addresses
if (!IPAddress.TryParse(token, out var ip)) return null;
if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4();
foreach (var range in NonPublic)
{
if (range.Contains(ip)) return null;
}
return ip.ToString();
}
}
Two details matter here. IPAddress.TryParse happily accepts legacy forms: "8.8" becomes 8.0.0.8 and "134744072" becomes 8.8.8.8. A strict dotted-quad check stops a garbage log field from turning into a real, billable address. And IPNetwork (new in .NET 8) handles the range checks for both IPv4 and IPv6, so there's no hand-rolled bit math.
If your app sits behind a CDN or load balancer, the first field of the log is the proxy, not the visitor. Configure the web server to log the real client address (Nginx's real_ip module, or ASP.NET Core's forwarded headers middleware with your proxies listed as trusted) before you run any of this.
Step 2: look the addresses up in bulk
The response models come first. The full response carries 30 fields per address (flags, provider names, confidence scores, last-seen dates); these classes keep the 16 the triage step reads.
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace LogVpnCheck;
public sealed class SecurityInfo
{
public int ThreatScore { get; init; }
public bool IsTor { get; init; }
public bool IsVpn { get; init; }
public List<string>? VpnProviderNames { get; init; }
public bool IsProxy { get; init; }
public bool IsResidentialProxy { get; init; }
public List<string>? ProxyProviderNames { get; init; }
public bool IsRelay { get; init; }
public string? RelayProviderName { get; init; }
public bool IsKnownAttacker { get; init; }
public bool IsKnownGoodBot { get; init; }
public string? BotOperatorName { get; init; }
public bool IsCloudProvider { get; init; }
public string? CloudProviderName { get; init; }
public bool IsCorporateGateway { get; init; }
public string? CorporateGatewayProviderName { get; init; }
}
// One element of the bulk response: a result, or a message for an entry the API skipped.
public sealed record BulkItem(string? Ip, SecurityInfo? Security, string? Message);
public sealed class LookupException(string message, int statusCode) : Exception(message)
{
public int StatusCode { get; } = statusCode;
}
JsonNamingPolicy.SnakeCaseLower, also new in .NET 8, maps ThreatScore to threat_score without an attribute on every property. Entries the API refuses (a private address that slipped through, say) come back as an object with only a message field, which is why BulkItem has one.
The client sends 1,000 addresses per request and keeps going when one batch fails:
public sealed class SecurityClient(HttpClient http, string apiKey)
{
public const int BatchSize = 1000;
private const string Endpoint = "https://api.ipgeolocation.io/v3/security-bulk";
// Ask only for what the triage step reads; it keeps a 1,000-IP response small.
private const string Fields =
"security.threat_score,security.is_tor,security.is_vpn,security.vpn_provider_names," +
"security.is_proxy,security.is_residential_proxy,security.proxy_provider_names," +
"security.is_relay,security.relay_provider_name,security.is_known_attacker," +
"security.is_known_good_bot,security.bot_operator_name,security.is_cloud_provider," +
"security.cloud_provider_name,security.is_corporate_gateway," +
"security.corporate_gateway_provider_name";
private static readonly JsonSerializerOptions Json =
new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
public async Task<Dictionary<string, SecurityInfo>> LookupAsync(
IReadOnlyList<string> ips, CancellationToken ct = default)
{
var results = new Dictionary<string, SecurityInfo>(StringComparer.Ordinal);
foreach (var batch in ips.Chunk(BatchSize))
{
List<BulkItem> items;
try
{
items = await PostBatchAsync(batch, ct);
}
catch (Exception ex) when (IsTransient(ex) && !ct.IsCancellationRequested)
{
// Skip this batch and keep going; its IPs show up as "unknown" for a rerun.
Console.Error.WriteLine($"Skipped {batch.Length} IPs ({ex.GetType().Name}).");
continue;
}
foreach (var item in items)
{
if (item.Ip is not null && item.Security is not null)
results[item.Ip] = item.Security;
}
}
return results;
}
A timeout or a 5xx on one batch shouldn't throw away the other forty, so those batches are skipped and their addresses show up as unknown in the report. A 401 or 429 is different: retrying won't fix a bad key or an empty quota, so those stop the run.
private async Task<List<BulkItem>> PostBatchAsync(string[] batch, CancellationToken ct)
{
var url = $"{Endpoint}?apiKey={Uri.EscapeDataString(apiKey)}&fields={Fields}";
// JsonContent sets Content-Type: application/json; anything else gets HTTP 415.
using var content = JsonContent.Create(new { ips = batch });
using var response = await http.PostAsync(url, content, ct);
if (!response.IsSuccessStatusCode)
throw new LookupException(Describe(response.StatusCode), (int)response.StatusCode);
return await response.Content.ReadFromJsonAsync<List<BulkItem>>(Json, ct) ?? [];
}
private static bool IsTransient(Exception ex) =>
ex is TaskCanceledException or HttpRequestException or LookupException { StatusCode: >= 500 };
// Fixed messages only. The request URL carries the key, so no raw exception text gets logged.
private static string Describe(HttpStatusCode status) => (int)status switch
{
400 => "The API rejected the request body.",
401 => "The key was rejected or can't read security data.",
413 => "The batch is too large. Lower BatchSize.",
429 => "The key's quota is used up.",
>= 500 => "The lookup service failed. Try again later.",
_ => "The lookup failed.",
};
}
The error messages are fixed strings on purpose. The request URL carries the API key, so nothing in this code logs the URL or an exception's message, only the exception type and the status code. .NET's HttpClient exceptions don't include the URL, but if you move this into ASP.NET Core with IHttpClientFactory, the logging in Microsoft.Extensions.Http 8.x writes the full request URI, query string included, at Information level. Version 9.0 and later redact the query string. Check which one you reference.
Step 3: turn flags into a verdict
The verdict has three parts: a label for the kind of network, an action, and a detail such as the provider name.
namespace LogVpnCheck;
public sealed record Verdict(string Label, string Action, string Detail);
public static class Triage
{
// The label says what kind of network the IP is on; the action says how hard to look.
// None of the actions is "block": a log review feeds rules, it doesn't replace them.
public static Verdict Classify(SecurityInfo? s)
{
if (s is null) return new("unknown", "recheck", "");
if (s.IsKnownGoodBot) return new("good bot", "allow", s.BotOperatorName ?? "");
if (s.IsTor) return new("tor exit", "challenge", "");
if (s.IsResidentialProxy) return new("residential proxy", "review", First(s.ProxyProviderNames));
if (s.IsProxy) return new("proxy", "challenge", First(s.ProxyProviderNames));
if (s.IsVpn)
return new("vpn", s.IsKnownAttacker ? "challenge" : "watch", First(s.VpnProviderNames));
// Relays and company gateways put many ordinary people behind one address.
if (s.IsRelay) return new("privacy relay", "allow", s.RelayProviderName ?? "");
if (s.IsCorporateGateway)
return new("corporate gateway", "allow", s.CorporateGatewayProviderName ?? "");
if (s.IsCloudProvider)
return new("hosting", s.IsKnownAttacker ? "challenge" : "watch", s.CloudProviderName ?? "");
return new("no flags", s.IsKnownAttacker ? "watch" : "allow", "");
}
private static string First(List<string>? names) => names switch
{
null or [] => "",
[var only] => only,
[var first, ..] => $"{first} +{names.Count - 1}",
};
}
The order of the checks is deliberate. A declared search engine crawler wins first, because a security rule that blocks Googlebot is a very expensive way to find a bug. Residential proxies come before VPNs, because an address that's both (it happens) is the riskier of the two. Relays and corporate gateways land on allow, for reasons the last section covers.
Step 4: write the report
using System.Globalization;
using System.Text;
namespace LogVpnCheck;
public sealed record Row(string Ip, int Requests, int? ThreatScore, Verdict Verdict);
public static class Report
{
private static readonly string[] ActionOrder = ["review", "challenge", "recheck", "watch", "allow"];
// Most urgent first, then by score, then by how much traffic the IP sent.
public static List<Row> Build(
Dictionary<string, int> counts, Dictionary<string, SecurityInfo> lookups) =>
counts
.Select(c =>
{
lookups.TryGetValue(c.Key, out var s);
return new Row(c.Key, c.Value, s?.ThreatScore, Triage.Classify(s));
})
.OrderBy(r => Array.IndexOf(ActionOrder, r.Verdict.Action))
.ThenByDescending(r => r.ThreatScore ?? -1)
.ThenByDescending(r => r.Requests)
.ToList();
public static void WriteCsv(string path, IEnumerable<Row> rows)
{
var sb = new StringBuilder();
sb.AppendLine("ip,requests,threat_score,label,action,detail");
foreach (var r in rows)
{
sb.AppendLine(string.Join(',',
r.Ip,
r.Requests.ToString(CultureInfo.InvariantCulture),
r.ThreatScore?.ToString(CultureInfo.InvariantCulture) ?? "",
Csv(r.Verdict.Label),
r.Verdict.Action,
Csv(r.Verdict.Detail)));
}
File.WriteAllText(path, sb.ToString());
}
public static void PrintTop(IReadOnlyList<Row> rows, int count)
{
Console.WriteLine($"{"IP",-16} {"Req",5} {"Score",5} {"Label",-18} {"Action",-9} Detail");
foreach (var r in rows.Take(count))
{
var score = r.ThreatScore?.ToString(CultureInfo.InvariantCulture) ?? "-";
Console.WriteLine(
$"{r.Ip,-16} {r.Requests,5} {score,5} {r.Verdict.Label,-18} {r.Verdict.Action,-9} {r.Verdict.Detail}");
}
}
// Provider names come from outside your system: quote commas ("Akamai Technologies, Inc.")
// and defuse values a spreadsheet would run as a formula.
public static string Csv(string value)
{
if (value.Length > 0 && "=+-@".Contains(value[0])) value = "'" + value;
return value.IndexOfAny([',', '"', '\n', '\r']) < 0
? value
: $"\"{value.Replace("\"", "\"\"")}\"";
}
}
Provider names come from outside your system, so the CSV writer quotes commas and defuses anything that starts like a spreadsheet formula. Akamai Technologies, Inc. would otherwise split into two columns, and a crafted name starting with = would be evaluated as a formula when someone opens the file in Excel.
Program.cs wires it together:
using LogVpnCheck;
var apiKey = Environment.GetEnvironmentVariable("IPGEO_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.Error.WriteLine("Set the IPGEO_API_KEY environment variable first.");
return 1;
}
var logPath = args.Length > 0 ? args[0] : "access.log";
var csvPath = args.Length > 1 ? args[1] : "ip-triage.csv";
// One HttpClient for the whole run. The timeout covers a full 1,000-IP batch.
using var http = new HttpClient(new SocketsHttpHandler
{
ConnectTimeout = TimeSpan.FromSeconds(5),
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
})
{
Timeout = TimeSpan.FromSeconds(60),
};
try
{
var counts = LogReader.CountClientIps(File.ReadLines(logPath));
Console.WriteLine($"{counts.Count} public client IPs in {logPath}");
var lookups = await new SecurityClient(http, apiKey).LookupAsync([.. counts.Keys]);
var rows = Report.Build(counts, lookups);
Report.WriteCsv(csvPath, rows);
Report.PrintTop(rows, 10);
Console.WriteLine($"Full results: {csvPath}");
return 0;
}
catch (LookupException ex)
{
// 401, 429 and malformed requests won't fix themselves, so stop instead of retrying.
Console.Error.WriteLine($"Lookup stopped (HTTP {ex.StatusCode}): {ex.Message}");
return 2;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Console.Error.WriteLine($"Couldn't read the log or write the CSV ({ex.GetType().Name}).");
return 3;
}
Run it
dotnet run -- access.log ip-triage.csv
Here's the output for a sample log of 499 lines, run against responses recorded on November 26, 2026. Scores move as networks change, so yours won't match exactly.
7 public client IPs in access.log
IP Req Score Label Action Detail
145.223.7.7 41 90 residential proxy review FleetProxy +10
185.220.101.1 17 95 tor exit challenge
51.15.0.1 230 5 hosting watch ONLINE SAS NL
172.225.32.1 9 50 privacy relay allow Apple Relay
104.28.47.1 3 50 privacy relay allow Apple Relay
66.249.66.1 120 15 good bot allow Google
73.162.10.20 12 0 no flags allow
Full results: ip-triage.csv
The health checker on 10.0.0.5 and the loopback lines never reached the API, and the address that sent 41 POST requests to /login sits at the top.
The CSV holds one row per address with the columns ip, requests, threat_score, label, action, and detail, so it opens cleanly in Excel or loads into a SIEM lookup table.
Reading the threat score
The score runs from 0 to 100, and this sample shows why it's a sort key and not a rule on its own. The Tor exit scored 95. The residential proxy, which eleven proxy networks have handed out over the past 30 days and which also works as a VPN exit, scored 90. Both deserve attention.
Then look at the middle. Both Apple Private Relay addresses scored 50 and carry the anonymous flag, which is fair: hiding the user's address is the product. If you'd set a block at 50, you'd have just blocked two Safari users and let the Scaleway address pull 230 product pages at a score of 5. The hosting flag on that address, plus 230 requests, says more than its score does.
So use the score to decide what a human looks at first, and the flags to decide what happens. The Triage class above is that idea in 20 lines.
False positives, and why I wouldn't hard-block
I wouldn't block anything from this report automatically. Here's what a blanket block catches besides attackers:
Privacy relays. iCloud Private Relay users are ordinary iPhone and Mac customers. One relay address carries traffic for many of them.
Corporate gateways. Companies route staff through a secure web gateway, so one address can front an entire workforce. Block it and you've blocked a customer's whole company.
Mobile carriers. Carrier-grade NAT puts many subscribers behind one public address, so per-IP limits and blocks hit people who've never met.
VPN customers. People use VPNs on hotel Wi-Fi, for work, or because they care about privacy. Most of them want to buy something.
Stale data. An address flagged as a proxy last month may be a normal home line today. The last-seen dates in the full response exist for this.
What works better is proportional friction. Challenge (CAPTCHA, email or SMS code) on login, signup, and checkout when an address is a proxy or Tor exit. Loosen per-IP rate limits for relays and gateways instead of tightening them. Send residential proxies on high-value actions to review. Block on behavior, such as the Tor exit hammering /wp-login.php, not on the label alone.
Summary
To tell whether an IP in your logs is a VPN or proxy, check who owns the network, compare it against the public Tor, Apple, and cloud lists, and look it up against data built from watching VPN and proxy exits. The .NET tool here does that for a whole access log in one pass: strict parsing, bulk lookups of 1,000 addresses, fixed error messages that never leak the key, and a CSV sorted by what needs attention. Run it on last week's log, read the top ten rows yourself, and only then decide which of them deserve a rule.
Join the conversation! Your thoughts help the community grow.