Friday, March 26, 2010

City State Country and more From IP Address ASP.NET

IP Address Details in XML Format.

I check too many sites for free IP details provides, But i didn't get a good one. finally i got a url "" thats work fine and get correct details including City, State, Country, Latitude, Longitude, Timezone and more from IP Address.

The request url is "" . Response comes in XML format. using xml deserialize i deserialize the response.

Below image shown the XML response

To get IPAddress of a client machine using ASP.NET is
string ipAddress = HttpContext.Current.Request.UserHostAddress;

Main classes

IPLocater class contains all properties of XML Response.this class is used for desirialization.

[XmlRootAttribute(ElementName = "Response", IsNullable = false)]

public class IPLocator

private string longitude;
public string Longitude
get { return longitude; }
set { longitude = value; }

private string latitude;
public string Latitude
get { return latitude; }
set { latitude = value; }

private string zip;
public string Zip
get { return zip; }
set { zip = value; }

private string ip;
public string IP
get { return ip; }
set { ip = value; }

After deserialization IPLocater class bind All properties of requested IP Address.

Binding Class is return IPLocater class.

Code of IPDetals Class

public class IPDetails

public IPLocator GetData(string ipAddress)
IPLocator ipLoc = new IPLocator();
string path = "" + ipAddress;
WebClient client = new WebClient();
string[] eResult = client.DownloadString(path).ToString().Split(',');
ipLoc = (IPLocator)Deserialize(eResult[0].ToString());
{ }
return ipLoc;

//Desrialize XML String

private Object Deserialize(String pXmlizedString)
XmlSerializer xs = new XmlSerializer(typeof(IPLocator));
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return xs.Deserialize(memoryStream);

//String to UTF8ByteArray
private Byte[] StringToUTF8ByteArray(String pXmlString)
UTF8Encoding encoding = new UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;


string ipAddress = HttpContext.Current.Request.UserHostAddress;
IPDetails ipDetails=new IPDetails ();
IPLocator ipLocater = ipDetails.GetData(ipAddress);

Download Source code