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
private string GetGeoLocationByIP(string strIPAddress)

        //Create a WebRequest
        WebRequest rssReq = WebRequest.Create("" + strIPAddress);

        //Create a Proxy
        WebProxy px = new WebProxy("" + strIPAddress, true);

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

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


            //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
            //United States
            //Mountain View

            DataTable dt = ds.Tables[0];

            if (dt != null && dt.Rows.Count > 0)
                      return dt.Rows[0]["CountryCode"].ToString();

           return String.Empty;
            return String.Empty;

Source : -


  1. I used the above code in my project but the XML Reader returns None. Please suggest

  2. does not exist!
    The requested URL / was not found on this server.