Tuesday, December 11, 2012

Get Client IP,Country and Code using WebService


To get the Client IP related information we can use a free webservice available here.
Add the webservice reference to your project and add the below method.


private void GetUserIP()
{
string UIP= Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];
net.webservicex.www.GeoIPService myProxy = new net.webservicex.www.GeoIPService();
List<net.webservicex.www.GeoIP> resultList = new List<net.webservicex.www.GeoIP>();
resultList.Add(myProxy.GetGeoIP(UIP));
Response.Write("User IP: " + UIP + "<br/>");
Response.Write("Country Name: "+resultList[0].CountryName+"<br/>");
Response.Write("Country Code: " + resultList[0].CountryCode);
}

Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];

This will get the ip address of the client.

net.webservicex.www.GeoIPService myProxy = new net.webservicex.www.GeoIPService()
Create an object from the webservice reference.

List<net.webservicex.www.GeoIP> resultList = new List<net.webservicex.www.GeoIP>()
Get an IEnumerable type of result.

myProxy.GetGeoIP(UIP)
Pass the user IP address.

Below Code will Print the User IP Country name and Code.

Response.Write("User IP: " + UIP + "<br/>");
Response.Write("Country Name: "+resultList[0].CountryName+"<br/>");
Response.Write("Country Code: " + resultList[0].CountryCode);


Output:
User IP: 61.245.168.13
Country Name: Sri Lanka
Country Code: LKA

No comments:
Write comments
Recommended Posts × +