To get country/geo location of a user using C# MVC, client IP

By Pranay
30 Aug '20  ·  27393 views

If you would like to know the geo location of the client who is visiting your website or to show some specific content based on visitor country/location then this article helps you.

To know the country name, we need to get the IP address of the user and check with the Geo location database to get the location/country based on the IP address. The geo location database is available with many geo location providers. Either we can run that instance in our own server or call the geo location provider API to get the location details.

Note: All the Geolocation providers get the location details based on the IP address. So if the user if spoofing his IP address, then we might get a different location.

Although there are many geo location providers in the market, in this example we will consider the ipstack.com (https://ipstack.com/) API to get the geolocation. ipstack.com provides a free plan as well with limitation of 10k queries per month. If you think you might send more requests then check the ipstack pricing here to avail more requests.

Steps

1. Getting the client IP address.

Use the below code to get the client IP address. i.e., the IP address of the machine which requested a page in your website.

String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
    UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

2. Calling the ipstack.com API

Below is the format we need to use for the API URL.

api.ipstack.com/{IPAddress_or_hostname}?access_key={xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}

access_key –> this is the secret access key provided by ipstack when we signup with them for an account (both free and premium).

For example, if we like to get the location details with IP address then we could use the API URL as 'http://api.ipstack.com/17.236.44.207?access_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

Similarly using hostname as 'http://api.ipstack.com/logicalfeed.com?access_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

string url = "http://api.ipstack.com/" + UserIP.ToString() + "/" + AccessKey.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);

3. Reading the Geo location details from the response.

To get the sample response format, run this "http://api.ipstack.com/XX.XX.XX.XX?access_key=ACCESS_KEY" (replace XX.XX.XX.XX with the required IP address & ACCESS_KEY with ipstack access key) URL directly in the browser. You will see the below response format.

{"ip":"2607:f1c0:100f:f000::2f4","type":"ipv6","continent_code":"NA","continent_name":"North America","country_code":"US","country_name":"United States","region_code":"PA","region_name":"Pennsylvania","city":"Wayne","zip":"19087","latitude":40.043800354003906,"longitude":-75.38829803466797,"location":{"geoname_id":5218270,"capital":"Washington D.C.","languages":[{"code":"en","name":"English","native":"English"}],"country_flag":"http:\/\/assets.ipstack.com\/flags\/us.svg","country_flag_emoji":"\ud83c\uddfa\ud83c\uddf8","country_flag_emoji_unicode":"U+1F1FA U+1F1F8","calling_code":"1","is_eu":false}}

Getting location details using geoip

Use the below code to convert the response to JSON object and then read the values of JSON object and save to a session variable or some other variable.

dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["LocId"] = dynObj.country_code;

Final Code

String AccessKey = "";
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
    UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://api.ipstack.com/" + UserIP.ToString() + "?access_key=" + AccessKey;
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;

About the author

Pranay Deegoju
Sitecore Certified Professional

A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.


Post a comment


Recent Posts

×

Liked this article?

Subscribe with your email and get updates when ever a new article is posted.

By subscribing you agree to our privacy terms. We promise that we do not sell your data.