简体   繁体   中英

How to find country from ip adress?

I am using this API to find the country of a user. I am able to find the country on a web page in XML format. Here you can see XML file example. But the problem is i can not read this XML in my c# code. Here is my code

string UserIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
string ApiKey = "5d3d0cdbc95df34b9db4a7b4fb754e738bce4ac914ca8909ace8d3ece39cee3b";
string Url = "http://api.ipinfodb.com/v3/ip-country/?key=" + ApiKey + "&ip=" + UserIP;
XDocument xml = XDocument.Load(Url);

But this code returns following exception on loading the xml.

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

Please describe the exact method to read this XML.

I'll say that it isn't an XML but simply a string subdivided by ; :

By giving an impossible IP address we can see that it's so composed:

OK;;74.125.45.100;US;UNITED STATES
ERROR;Invalid IP address.;127.0.0.1.1;;

OK/ERROR
If ERROR, complete ERROR message
IP Address
Abbreviation of country
Country name

This code should do:

string userIP = "127.0.0.1";
string apiKey = "5d3d0cdbc95df34b9db4a7b4fb754e738bce4ac914ca8909ace8d3ece39cee3b";
string url = "http://api.ipinfodb.com/v3/ip-country/?key=" + apiKey + "&ip=" + userIP;

WebRequest request = WebRequest.Create(url);

using (var response = (HttpWebResponse)request.GetResponse())
{
    // We try to use the "correct" charset
    Encoding encoding = response.CharacterSet != null ? Encoding.GetEncoding(response.CharacterSet) : null;

    using (var sr = encoding != null ? new StreamReader(response.GetResponseStream(), encoding) :
                                       new StreamReader(response.GetResponseStream(), true))
    {
        var response2 = sr.ReadToEnd();
        var parts = response2.Split(';');

        if (parts.Length != 5)
        {
            throw new Exception();
        }

        string okError = parts[0];
        string message = parts[1];
        string ip = parts[2];
        string code = parts[3];
        string country = parts[4];
    }
}

Here is what I'd do:

  • Using a HTTP transfer, query the site, and buffer the results
  • Convert it into a String
  • Use a splitting algorithm on it to make into an array.
  • Check if the 0th element of the array equals 'OK'
  • If not, bail out.
  • If so, check the third and fourth elements for country code, and country name respectively.

from the IP Location XML API Documentation : API Parameter format, required = false, default = raw, values = raw, xml, json. so I have tested it and string Url = "http://api.ipinfodb.com/v3/ip-country/?key=" + ApiKey + "&ip=" + UserIP + "&format=xml" gives a parsable xml result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM