Search code examples
c#asp.net-mvcgeolocationip

Http Get Request for IpDBInfo using an IP Address


I am working on a web application and it needs to track a location using an IP Address and I am new to sending requests to some APIs and getting a response from them. I was able to retrieve IP address of the user using Request.UserHostAddress and was able to validate it using the following C# code

if (System.Text.RegularExpressions.Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4 || ips.Length == 6)
                {
                    if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256
                        & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                        return true;
                    else
                        return false;
                }
                else
                    return false;
            }
            else
                return false;

and I have got the API key and IP address required to request the following API

http://api.ipinfodb.com/v2/ip_query.php?key=[API KEY]&ip=[IP Address]&timezone=false

I know an HTTP GET REQUEST to the above would give me an XML response but not sure how to get started with the HTTP REQUEST in ASP.NET MVC using C#.

Can someone help me get started with this?


Solution

  • The response of IPInfoDB is a string like below:

    OK;;74.125.45.100;US;United States;California;Mountain View;94043;37.406;-122.079;-07:00

    So we need to split into the various fields using C# codes below.

            string key = "Your API key";
            string ip = "IP address to check";
            string url = "http://api.ipinfodb.com/v3/ip-city/?key=" + key + "&ip=" + ip;
    
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
    
            webReq.Method = "GET";
    
            HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
    
            Stream answer = webResponse.GetResponseStream();
    
            StreamReader response = new StreamReader(answer);
    
            string raw = response.ReadToEnd();
    
            char[] delimiter = new char[1];
    
            delimiter[0] = ';';
    
            string[] rawdata = raw.Split(delimiter);
    
            ViewData["Response"] = "Country Code: " + rawdata[3] + " Country Name: " + rawdata[4] + " State: " + rawdata[5] + " City: " + rawdata[6];
    
            response.Close();