Monday, March 21, 2011

Get Client Geo Location in C#

Get Client Geo Location in C#


There are two things to do in order to get the Geo location of a request client.
1,  Get the IP address of the request using below code...
string strClientIP = Request.ServerVariables["REMOTE_ADDR"].Trim();
2, Get the country code by calling free webservice, as an example, I am using freegeoip.appspot.com.
private string GetGeoLocationByIP(string strIPAddress)
{

        //Create a WebRequest
        WebRequest rssReq = WebRequest.Create("http://freegeoip.appspot.com/xml/" + strIPAddress);

        //Create a Proxy
        WebProxy px = new WebProxy("http://freegeoip.appspot.com/xml/" + strIPAddress, true);

        //Assign the proxy to the WebRequest
        rssReq.Proxy = px;

        //Set the timeout in Seconds for the WebRequest
        rssReq.Timeout = 2000;

        try
        {

            //Get the WebResponse

            WebResponse rep = rssReq.GetResponse();

            //Read the Response in a XMLTextReader

            XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());

            //Create a new DataSet

            DataSet ds = new DataSet();

            //Read the Response into the DataSet
            //true
            //72.14.247.141
            //US
            //United States
            //CA
            //California
            //Mountain View
            //94043
            //37.4192
            //-122.057

            ds.ReadXml(xtr);
            DataTable dt = ds.Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
              
                if(dt.Rows[0]["Status"].ToString().Equals("true",StringComparison.CurrentCultureIgnoreCase))
                {
                      return dt.Rows[0]["CountryCode"].ToString();

                }      
           }
           return String.Empty;
        catch
        {
            return String.Empty;
        }
}


Source : - http://mypath2us.com/post/2009/10/18/Get-Client-Geo-Location-in-C.aspx

1 comment:

  1. http://freegeoip.appspot.com does not exist!
    The requested URL / was not found on this server.

    ReplyDelete