Smart way to get the public Internet IP address/geo loc

后端 未结 9 2017
野趣味
野趣味 2021-01-01 05:41

I have a computer on the local network, behind a NAT router. I have some 192.168.0.x addresses, but I really want to know my public IP address, not somethin

9条回答
  •  长发绾君心
    2021-01-01 06:28

    I do it like this: I create a class that holds the geo location data

    [Serializable]
    public class LocationData
    {
         public string IP { get; set; }
         public string CountryCode { get; set; }
         public string CountryName { get; set; }
         public string RegionCode { get; set; }
         public string City { get; set; }
         public string ZipCode { get; set; }
         public string TimeZone { get; set; }
         public string Latitude { get; set; }
         public string Longitude { get; set; }
         public string MetroCode { get; set; }
    }
    

    then I use the following code to call the geo data and fill the class.

    public static LocationData GetLocation(string ip= "")
    {
        using (var client = new System.Net.WebClient())
        {
             XmlRootAttribute xRoot = new XmlRootAttribute();
             xRoot.ElementName = "Response";
             string downloadedString = client.DownloadString("http://freegeoip.net/xml/" + ip);
               XmlSerializer mySerializer = new XmlSerializer(typeof(LocationData), xRoot) ;
            using (XmlReader xmlReader = XmlReader.Create(new System.IO.StringReader(downloadedString)))
            {
                 return mySerializer.Deserialize(xmlReader)as LocationData;
            }
         }
    }
    

    as the answer is "bad" xml one needs to specify the xRoot element or one gets an error.

    Happy coding

    Walter

提交回复
热议问题