To determine the usage type of an IP address using IP2Location.io in C#, you can use the IP2Location.io API to retrieve geolocation and related data. The usage type field specifies how the IP is being used. For usage types supported, please see API documentation for more info.
dotnet new console
dotnet add package Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
HttpClient client = new();
string ip = "8.8.8.8";
string key = "YOUR_API_KEY";
try
{
HttpResponseMessage response = await client.GetAsync($"https://api.ip2location.io/?key={key}&ip={ip}&format=json");
if (response.StatusCode == HttpStatusCode.OK)
{
string rawjson = await response.Content.ReadAsStringAsync();
JObject? results = JsonConvert.DeserializeObject<JObject>(rawjson);
if (results != null)
{
if (results["usage_type"] != null)
{
Console.WriteLine($"The usage type for IP {ip} is {results["usage_type"]}.");
}
else
{
throw new Exception("ERROR: The usage_type field requires a paid subscription to the Starter plan or higher.");
}
}
else
{
throw new Exception("ERROR: Invalid JSON in response.");
}
}
else if ((response.StatusCode == HttpStatusCode.Unauthorized) || (response.StatusCode == HttpStatusCode.BadRequest))
{
string rawjson = await response.Content.ReadAsStringAsync();
if (rawjson.Contains("error_message"))
{
JObject? results = JsonConvert.DeserializeObject<JObject>(rawjson);
throw new Exception($"ERROR: {results?["error"]?["error_message"]?.ToString()}");
}
throw new Exception(rawjson);
}
}
catch (HttpRequestException ex)
{
throw new Exception(ex.Message);
}
dotnet run
This script will output the usage type of specified IP address. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.
Empower your applications with accurate IP geolocation information now.
Try It for Free