Smart way to get the public Internet IP address/ge

2019-02-07 11:21发布

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 something mentioned in

How to get the IP address of the server on which my C# application is running on?

or

How to get the IP address of a machine in C#

I need C# code.

Is it possible? If so, how?

9条回答
Fickle 薄情
2楼-- · 2019-02-07 11:49

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

查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-07 11:50

After some search, and by expanding my requirements, I found out that this will get me not only the IP, but GEO-location as well:

class GeoIp
{
    static public GeoIpData GetMy()
    {
        string url = "http://freegeoip.net/xml/";
        WebClient wc = new WebClient();
        wc.Proxy = null;
        MemoryStream ms = new MemoryStream(wc.DownloadData(url));
        XmlTextReader rdr = new XmlTextReader(url);
        XmlDocument doc = new XmlDocument();
        ms.Position = 0;
        doc.Load(ms);
        ms.Dispose();
        GeoIpData retval = new GeoIpData();
        foreach (XmlElement el in doc.ChildNodes[1].ChildNodes)
        {
            retval.KeyValue.Add(el.Name, el.InnerText);
        }
        return retval;
    }
}

XML returned, and thus key/value dictionary will be filled as such:

<Response>
    <Ip>93.139.127.187</Ip>
    <CountryCode>HR</CountryCode>
    <CountryName>Croatia</CountryName>
    <RegionCode>16</RegionCode>
    <RegionName>Varazdinska</RegionName>
    <City>Varazdinske Toplice</City>
    <ZipCode/>
    <Latitude>46.2092</Latitude>
    <Longitude>16.4192</Longitude>
    <MetroCode/>
</Response>

And for convenience, return class:

class GeoIpData
{
    public GeoIpData()
    {
        KeyValue = new Dictionary<string, string>();
    }
    public Dictionary<string, string> KeyValue;
}
查看更多
爷的心禁止访问
4楼-- · 2019-02-07 11:51

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.

查看更多
祖国的老花朵
5楼-- · 2019-02-07 11:58

I prefer http://icanhazip.com. It returns a simple text string. No HTML parsing required.

string myIp = new WebClient().DownloadString(@"http://icanhazip.com").Trim();
查看更多
Explosion°爆炸
6楼-- · 2019-02-07 11:58

If you are worried about connection lose or the availability of the site, you can also try this way to avoid that issue by including above suggestions.

    using System.Threading;

    Task<string>[] tasks = new[]
    {
      Task<string>.Factory.StartNew( () => new System.Net.WebClient().DownloadString(@"http://icanhazip.com").Trim() ),
      Task<string>.Factory.StartNew( () => new System.Net.WebClient().DownloadString(@"http://checkip.dyndns.org").Trim() )
    };

    int index = Task.WaitAny( tasks );
    string ip = tasks[index].Result;

Hope this one also help.

查看更多
做自己的国王
7楼-- · 2019-02-07 12:01

I believe you really need to connect with some server to get your external IP.

查看更多
登录 后发表回答