Adsence750x90

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 "http://ipinfodb.com/" thats work fine and get correct details including City, State, Country, Latitude, Longitude, Timezone and more from IP Address.

The request url is "http://ipinfodb.com/ip_query.php?ip=IPADDR" . 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();
try
{
string path = "http://ipinfodb.com/ip_query.php?ip=" + ipAddress;
WebClient client = new WebClient();
string[] eResult = client.DownloadString(path).ToString().Split(',');
if(eResult.Length>0)
ipLoc = (IPLocator)Deserialize(eResult[0].ToString());
}
catch
{ }
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;
}
}


Implementation


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



Download Source code

1 comment:

Seetha said...

Thank you for your informations.... I got this site http://www.whoisxy.com/for the IP address search details search.... Its very useful for the best conversations with the IP address to domain name and domain name to IP address.... In here we can get the DNS services and best domain name registration...