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

后端 未结 9 1978
野趣味
野趣味 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

    The problem is that the IP address you're looking for doesn't belong to your computer. It belongs to your NAT router. The only ways I can think of getting it is to use an external server or have some way of querying your router.

    If your router supports SNMP, you may be able to get it that way.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-01 06:30

    Below code will help you to take public IP address

        string _externalIP;
        _externalIP = (new WebClient()).DownloadString("http://http://icanhazip.com/");
        _externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                     .Matches(externalIP)[0].ToString();
    
    0 讨论(0)
提交回复
热议问题