How to geolocate an IP using C# in .NET Framework
IP address geolocation can be crucial for many projects, useful for blocking potentially dangerous web traffic, providing shipping estimates, and gathering customer data, just to name a few. While setting up a geolocation function is by no means trivial, there is a much easier alternative that we will be looking at in today’s post: employing an API.
First, install the API client we will be using by running this command in the console of Package Manager:
Install-Package Cloudmersive.APIClient.NET.Validate -Version 1.2.7
Now we just have to call IPAddressPost:
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.Validate.Api;
using Cloudmersive.APIClient.NET.Validate.Client;
using Cloudmersive.APIClient.NET.Validate.Model;namespace Example
{
public class IPAddressPostExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new IPAddressApi();
var value = value_example; // string | IP address to geolocate, e.g. \"55.55.55.55\". The input is a string so be sure to enclose it in double-quotes.try
{
// Geolocate an IP address
GeolocateResponse result = apiInstance.IPAddressPost(value);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling IPAddressApi.IPAddressPost: " + e.Message );
}
}
}
}
Let’s look at the output for this example IP address: 1.160.10.240
{
"CountryCode": "TW",
"CountryName": "Taiwan",
"City": "Taipei",
"RegionCode": "TPE",
"RegionName": "Taipei City",
"ZipCode": "",
"TimezoneStandardName": "Asia/Taipei",
"Latitude": 25.0478,
"Longitude": 121.5318
}
As you can see, a lot of useful information is given about the IP address in question.