To determine the ISP of an IP address using IP2Location.io in C#, you can use the IP2Location.io API to retrieve geolocation and related data.
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["isp"] != null)
{
Console.WriteLine($"The ISP for IP {ip} is {results["isp"]}.");
}
else
{
throw new Exception("ERROR: The isp 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 ISP 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