Table of Contents

VpnHood.Net.IpLocations

IP location for .NET: find the country, and where known the region and city, of an IP address or of the device's own public address, from online services or from a local database. It is the location layer of VpnHood: the app finds its country and the IP ranges of the countries it splits the tunnel by, and a server finds its own country. It works for any app that needs to place an address.

dotnet add package VpnHood.Net.IpLocations

How it works

Quick start

The examples below run as a test in CI (IpLocationsReadmeExampleTest.cs). Their namespaces are System.Net, VpnHood.Net.IpLocations.Providers.Offlines and VpnHood.Net.Toolkit.Net.

Look up an address locally

// IP ranges with their countries: two here; in an app, IP2Location's database (Ip2LocationDbParser)
using var provider = new LocalIpLocationProvider([
    new LocalIpLocationProvider.IpRangeInfo {
        IpRange = new IpRange(IPAddress.Parse("1.0.0.0"), IPAddress.Parse("1.0.0.255")),
        CountryCode = "AU"
    },
    new LocalIpLocationProvider.IpRangeInfo {
        IpRange = new IpRange(IPAddress.Parse("5.0.0.0"), IPAddress.Parse("5.0.0.255")),
        CountryCode = "DE"
    }
]);

var location = await provider.GetLocation(IPAddress.Parse("5.0.0.10"), CancellationToken.None);
Console.WriteLine($"{location.CountryName} ({location.CountryCode})"); // Germany (DE)

Save and load the ranges

var path = Path.GetTempFileName(); // in an app, a file in its data folder

// save the ranges once, in their compact binary form...
await using (var file = File.Create(path))
    provider.Serialize(file);

// ...and load them when the app starts
using var loaded = LocalIpLocationProvider.Deserialize(File.OpenRead(path));

Packages

Requires .NET 11.