65.9K
CodeProject is changing. Read more.
Home

Finding Countries and Cities Using IP Address

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.69/5 (12 votes)

Aug 28, 2006

viewsIcon

56660

downloadIcon

1880

A simple article on finding the names of countries and cities using IP address, using www.showmyip.com (Note: free for only 199 request/day).

Introduction

This article describes how to find the names of countries and cities using the IP address.

Using the code

The code is given below with explanations:

//this line is to check the clien ip address from the server itself
string IP = Request.ServerVariables["REMOTE_ADDR"];

//Initializing a new xml document object to begin reading the xml file returned
XmlDocument doc = new XmlDocument();

//NOTE: www.showmyip.com only allows 199 request/day 
//as a free call, for more requests u could register with them
/////////////////

//send the request to www.showmyip.com sending the ip as a query string
//and loads the xml file in the document object
doc.Load("http://www.showmyip.com/xml/?ip=" + IP);

//begin finding the country by tag name
XmlNodeList nodeLstCountry = doc.GetElementsByTagName("lookup_country");

////begin finding the city by tag name
XmlNodeList nodeLstCity = doc.GetElementsByTagName("lookup_city2");

//concatinating the result for show, u could also use it
//to save in data base
IP = "Country :" + nodeLstCountry[0].InnerText + 
     " --  City :" + nodeLstCity[0].InnerText + "" + IP;
Response.Write(IP);

//this is my header that I love
Page.Header.Title = "I am muslim before anything";