In this short article I will explain how to get Country Name from IP Address in ASP.Net using C# and VB.Net.
The country name will be determined from IP Address using a Web Service.
The WebService
I am making use of the following free Web Service used for finding the geographical location of an IP Address.
Adding Reference of the Web Service in Visual Studio
1. Right click the project in Solution Explorer and choose Add Service Reference option from the context menu.
2. Now in the Add Service Reference Dialog you need to click on the Advanced button.
3. In the Service Reference Settings Dialog you need to click on Add Web Reference button.
4. Now in the Add Web Reference Dialog you need to add the URL of the Web Service and click the Green Go button to discover it. Once the Web Service is discovered, give its reference an appropriate name using the Web Reference Name TextBox and click on Add Reference button.
5. Finally you will notice the Web Service Reference has been added to your project.
Accessing the Web Service and its Methods
Using the Web Reference Name given in step #4, you can access the Web Service and its methods.
HTML Markup
The HTML Markup consists of a TextBox, a Button and a Label control.
<asp:TextBox ID="txtIPAddress" runat="server" Text="" />
<asp:Button Text="Submit" runat="server" OnClick="GetCountry" />
<hr />
<asp:Label ID="lblCountry" runat="server" />
Fetching the location from the Web Service
Inside the Button click event handler, an object of GeoIPService is created and then IP Address is passed as parameter to the GetGeoIP method which returns the name of the Country to which the IP address belongs. It is then displayed using the Label control.
C#
protected void GetCountry(object sender, EventArgs e)
{
GeoService.GeoIPService service = new GeoService.GeoIPService();
GeoService.GeoIP output = service.GetGeoIP(txtIPAddress.Text.Trim());
lblCountry.Text = "Country: " + output.CountryName;
}
VB.Net
Protected Sub GetCountry(sender As Object, e As EventArgs)
Dim service As New GeoService.GeoIPService()
Dim output As GeoService.GeoIP = service.GetGeoIP(txtIPAddress.Text.Trim())
lblCountry.Text = "Country: " + output.CountryName
End Sub
Demo
Downloads