Get GeoLocation for IP address C#

posted in: Tools | 0

This guide covers how to get GeoLocation and other information for an IP address. The api used in this guide is http://ip-api.com with JSON response format. ip-api.com provides a free usage for non-commercial usage with usage limit upto 150 requests per minute.  The main reason for choosing ip-api.com is the detailed response which it provides, read more at http://ip-api.com/docs/

 

Other Commercial Free sources includes:

  1. freegeoip.net
  2. geoip.nekudo.com
  3. ipinfo.io (1000 free requests daily)

Implementation Steps to Get GeoLocation for IP :

Step 1: Getting response format from the Api Provider

Following is the response format for the query

[javascript] {
"status": "success",
"country": "COUNTRY",
"countryCode": "COUNTRY CODE",
"region": "REGION CODE",
"regionName": "REGION NAME",
"city": "CITY",
"zip": "ZIP CODE",
"lat": LATITUDE,
"lon": LONGITUDE,
"timezone": "TIME ZONE",
"isp": "ISP NAME",
"org": "ORGANIZATION NAME",
"as": "AS NUMBER / NAME",
"query": "IP ADDRESS USED FOR QUERY"
}
[/javascript]

For instance for IP – 208.80.152.201  http://ip-api.com/json/208.80.152.201

[javascript] {
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "CA",
"regionName": "California",
"city": "San Francisco",
"zip": "94105",
"lat": "37.7898",
"lon": "-122.3942",
"timezone": "America\/Los_Angeles",
"isp": "Wikimedia Foundation",
"org": "Wikimedia Foundation",
"as": "AS14907 Wikimedia US network",
"query": "208.80.152.201"
}
[/javascript]

 

Step 2: Create a class from the response

You could use json2csharp for creation, just paste in the response json and a class would be automatically created.

[csharp] public class IPData
{
public string status { get; set; }
public string country { get; set; }
public string countryCode { get; set; }
public string region { get; set; }
public string regionName { get; set; }
public string city { get; set; }
public string zip { get; set; }
public string lat { get; set; }
public string lon { get; set; }
public string timezone { get; set; }
public string isp { get; set; }
public string org { get; set; }
public string @as { get; set; }
public string query { get; set; }
}
[/csharp]

Step 3: Include Json.Net Library in Project

Include Json.Net library by Newtonsoft for Deserializing response json.

This could be done by

[csharp]Install-Package Newtonsoft.Json[/csharp]

or adding the following in project.json if your project uses one.

[javascript]"Newtonsoft.Json" : "8.0.3" [/javascript]

Step 4:  Make an Api call and Deserialize response

Make an api call (GET Request) with the desired ip using webclient and deserialize the response JSON.

[csharp] WebClient client = new WebClient();

// Make an api call and get response.
string response = client.DownloadString("http://ip-api.com/json/208.80.152.201");

//Deserialize response JSON
IPData ipdata = JsonConvert.DeserializeObject<IPData>(response);
[/csharp]

Here’s a complete code, also available at dotnetfiddle https://dotnetfiddle.net/4LRFYp:

[csharp] using System;
using System.Net;
using Newtonsoft.Json;

public class GetGeoLocation
{
public IPData GetIPGeoLocation(string IP)
{
WebClient client = new WebClient();
// Make an api call and get response.
try
{
string response = client.DownloadString("http://ip-api.com/json/" + IP);
//Deserialize response JSON
IPData ipdata = JsonConvert.DeserializeObject<IPData>(response);
if (ipdata.status == "fail")
{
throw new Exception("Invalid IP");
}

return ipdata;
}
catch (Exception)
{
throw;
}
}

public static void Main()
{
IPData ipdata = new GetGeoLocation().GetIPGeoLocation("208.80.152.201");
Console.WriteLine(ipdata.status + " – Your IP belongs to ‘" + ipdata.region + " – " + ipdata.country + "’");
}
}
public class IPData
{
public string status { get; set; }
public string country { get; set; }
public string countryCode { get; set; }
public string region { get; set; }
public string regionName { get; set; }
public string city { get; set; }
public string zip { get; set; }
public string lat { get; set; }
public string lon { get; set; }
public string timezone { get; set; }
public string isp { get; set; }
public string org { get; set; }
public string @as { get; set; }
public string query { get; set; }
}
[/csharp]

How does IP Geo Locating work?

Mapping of IP addresses to geolocation is done is via tables, where an IP maps to a particular Geo Location. This is however approximated as the IP’s does not contains any information about their location. Below is an extract from ‘Geolocation software – Wikipedia‘.

The primary source for IP address data is the regional Internet registries which allocate and distribute IP addresses amongst organizations located in their respective service regions:

  • American Registry for Internet Numbers (ARIN)
  • RIPE Network Coordination Centre (RIPE NCC)
  • Asia-Pacific Network Information Centre (APNIC)
  • Latin American and Caribbean Internet Address Registry (LACNIC)
  • African Network Information Centre (AfriNIC)

 

Secondary sources include:

  • Data mining or user-submitted geographic location data. For example, a weather web site might ask visitors for a city name to find their local forecast. Another example would be to pair a user’s IP address with the address information in his/her account profile.
  • Data contributed by internet service providers.
  • Merging databases from different suppliers.
  • Guesstimates from adjacent Class C range[2] and/or gleaned from network hops.

Accuracy is improved by:

  • Data scrubbing to filter out or identify anomalies.
  • Statistical analysis of user submitted data.

 

How accurate is IP-based Geolocation?

Accuracy for geolocation database varies depending upon the granularity of the search. IP-to-country mapping is usually 98% – 99% accurate, whereas IP-to-Region (or City) mapping accuracy can range anywhere from 50% to 75%.

Leave a Reply

Your email address will not be published. Required fields are marked *