Saturday, June 21, 2008

Finding Country from Visitors IP in Asp.net

Finding Country Details from Visitors IP in Asp.net, C#

I want to develop a functionality which gives me

  • Visitor's Country details in Asp.net
  • Display Flag of Visitors Country based on Visitors IP Address
  • Gives Information about Visitors Country Currency Information
  • It should also provide Capital details of Visitors Country based on Visitors IP Address.

IP to Country Details

So lets understand step by step how we can Find Visitors Country Details based on Visitors IP Address

Step 1: Finding Visitor's IP Address in Asp.net, C# Code.

You can use following Code to find Visitors IP Address in Asp.net


string VisitorsIPAddr = string.Empty;
//Users IP Address.
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
//To get the IP address of the machine and not the proxy
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}

Step2: Finding Country based on Visitors IP Address.

To implement this functionality i have taken help of Code Project IP to Country Code developed by GameWatch Project

This is very well explained and explanatory code to implement. Let show you how I have use this code to Find Country Information from Visitors IP Address.

Download the Sourcecode file available with that code: Direct Download Link

  • Open folder util in zip file i.e. iptocountry_src\iptocountry\src\Utils, this folder contains 3 Class Files and One folder Net.
  • Now Add a new Class Library in your Website project and Add a this class file. Also create folder Net and include 2 class files in it.
After adding class library project your solution explorer looks like following:



Adding Resource File in your Web Application.
  • Now Open folder util in zip file i.e. iptocountry_src\iptocountry\resources, this folder contains 4 Resource Files add this file in your web application by creating new folder name IP2CountryResource
  • So by now your solution explorer should be looking as under.


Now next step would be how to add the resource file and access the classes to find country from given IP address details.
  • Add reference to Class Library Project in your web application.
  • Add following code on page where you want to display IP to country details.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using GameWatch.Utils;
using GameWatch.Utils.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
public IPToCountry Ip2Country = new IPToCountry();

protected void Page_Load(object sender, EventArgs e)
{
string sApplicationPath = Server.MapPath("~");

LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\apnic.latest");
LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\arin.latest");
LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\lacnic.latest");
LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\ripencc.latest");

#region Finding Visitors IP Address
string VisitorsIPAddr = string.Empty;
//Users IP Address.
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
//To get the IP address of the machine and not the proxy
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
#endregion

string VisitorsCountry = Ip2Country.GetCountry(VisitorsIPAddr);
lblVisitorsIP.Text = VisitorsIPAddr;
lblCountry.Text = VisitorsCountry;
}

public void LoadIpCountryTable(string name)
{
FileStream s = new FileStream(name, FileMode.Open);
StreamReader sr = new StreamReader(s);
Ip2Country.Load(sr);
sr.Close();
s.Close();
}
}

Now, lets understand how can we display visitors country flag and find visitors countries information.

Step 3: Displaying Visitors Country Information.
  • Displaying Flag from IP Address
  • Displaying Country Information from IP Address (i.e. Country Currency, Capital and few other information.)

Download Country details available in Excel File Format, and Download Zip Package consisting Flags of all countries shared as Free Resource by IP2Location.com

http://www.ip2location.com/free.asp

Import the Excel File format containing details of all countries in SQL Server Database (Choose database of your choice, I have used SQL Server 2005). For Importing excel file right click the database, choose tasks and than choose import data...



Than follow the wizard steps and table would be created.

Now, Add one more folder to VS.Net Web application and named it Flags
And add all the flags available with zip file you downloaded, so after adding all the flags .gif file solution explorer look as follow.



now add the code for accessing data from database based on country code you get from given IP Address.

Select Record based on TLD field, where TLD field is country code you receive from above code.

Sample Query.

SELECT DISTINCT [TLD], [Country], [FIPS104], [ISO2], [ISO3], [ISONo], [Capital], [Regions], [Currency], [CurrencyCode], [Population] FROM [Countries] WHERE ([TLD] = @TLD)

So now ones you are done with data access code you assign the available data source to DetailsView control. (Note: I have skip the data access code, You can refer this article if you are facing problem.)

Now just one line of code to actually display image in above code.

imgCountryFlag.ImageUrl = @"~/Flags/" + VisitorsCountry + ".gif";

9 comments:

Anonymous said...

Fantastic ! One question - if I want visitor to ban from certain IP is this possible ?

Please let me know.

DotNetGuts said...

OFcourse possible make a Table in database called banned IP each time user visit, check whether they are not belong BannedIP Table.

Anonymous said...

Cool nice article - got this working well on my machine, however I used a lookup function instead of table to get the country info.

Anonymous said...

nice article.. thanks

Anonymous said...

It is extremely interesting for me to read that article. Thanks for it. I like such topics and anything that is connected to them. I would like to read a bit more soon.

Anonymous said...

Keep on posting such themes. I like to read blogs like this. Just add some pics :)

Tanvi said...

Very Nice

mahesh said...

i want only visitors ip or userip to be shown in page or anywhere after execting the first code so where we see what so what should i do after execution where we can see ip
?

Rana Muhammmad Usman Feroze said...

Dear,

The code is extremely great. But you gave here the excel download link, which is now not working. Can you please post that excel file containing details of countries? Moreover, free flag images of all countries also do not exist.

Thank you so much.

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape