IP API - HTTP GET Request

  • Aug 04, 2021
  • 2
  • 1.3k

Sir,

There is one article of IP API - HTTP GET Request to get location based on IP address.

I am trying the same in a web application of framework 3.5 which is not in favour of HTTP Requests & Response.

Please advise 

Answers (2)

You can use ipstack API to get the geolocation for the given IP address using the .Net framework.

Please see the IPStack documentation.

Sample Code:

 private LocationDetails_IpStack GetGeolocationInfo(string ipAddress)
        {
            if (string.IsNullOrWhiteSpace(ipAddress))
            {
                ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (!string.IsNullOrEmpty(ipAddress))
                {
                    string[] ipRange = ipAddress.Split(',');
                    int le = ipRange.Length - 1;
                    string trueIP = ipRange[le];
                }
                else
                {
                    ipAddress = Request.ServerVariables["REMOTE_ADDR"];
                }              
            }

            LocationDetails_IpStack geolocationInfo = new LocationDetails_IpStack();
            var Ip_Stack_Url = "http://api.ipstack.com/" + ipAddress + "?access_key=<YOUR_KEY>";  // 192.180.210.42 - This is a sample IP address. You can pass yours if you want to test

            // Use HttpClient to get the details from the Json response
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                // Pass API address to get the Geolocation details 
                client.BaseAddress = new Uri(Ip_Stack_Url);
                HttpResponseMessage response = client.GetAsync(Ip_Stack_Url).GetAwaiter().GetResult();
                // If API is success and receive the response, then get the location details
                if (response.IsSuccessStatusCode)
                {
                    geolocationInfo = response.Content.ReadAsAsync<LocationDetails_IpStack>().GetAwaiter().GetResult();
                }
            }
            return geolocationInfo;
        }

 

By exploring comprehensive reviews from reputable sources, students can confidently utilize the platform to enhance their academic journey, secure in the knowledge of the quality and authenticity of the support they receive.

Submit your answer