获取公共互联网 IP 地址/地理位置的智能方法

发布于 2024-10-15 18:11:49 字数 332 浏览 3 评论 0原文

我在本地网络上有一台计算机,位于 NAT 路由器后面。我有一些 192.168.0.x 地址,但我真的想知道我的公共 IP 地址,而不是

中提到的内容如何获取运行 C# 应用程序的服务器的 IP 地址?

如何获取计算机的 IP 地址在 C# 中

我需要 C# 代码。

是否可以?如果是这样,怎么办?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

牵你手 2024-10-22 18:11:49

我更喜欢http://icanhazip.com。它返回一个简单的文本字符串。无需 HTML 解析。

string myIp = new WebClient().DownloadString(@"http://icanhazip.com").Trim();

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

string myIp = new WebClient().DownloadString(@"http://icanhazip.com").Trim();
黑寡妇 2024-10-22 18:11:49

经过一番搜索,并通过扩展我的要求,我发现这不仅会为我提供IP,而且还会为我提供地理位置:

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,因此键/值字典将这样填充:

<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>

为了方便起见,返回班级:

class GeoIpData
{
    public GeoIpData()
    {
        KeyValue = new Dictionary<string, string>();
    }
    public Dictionary<string, string> KeyValue;
}

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;
}
最笨的告白 2024-10-22 18:11:49

问题是您要查找的 IP 地址不属于您的计算机。它属于您的 NAT 路由器。我能想到的唯一方法是使用外部服务器或通过某种方式查询路由器。

如果您的路由器支持 SNMP,您也许可以通过这种方式获取它。

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.

与之呼应 2024-10-22 18:11:49

我相信你确实需要连接一些服务器来获取你的外部IP。

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

—━☆沉默づ 2024-10-22 18:11:49

根据您使用的路由器,您很可能可以直接从路由器获取它。它们中的大多数都有一个 Web 界面,因此只需导航到正确的网页(例如“192.168.0.1/无论什么”)并从该页面“抓取”外部 IP 地址即可。当然,这样做的问题是它非常脆弱——如果您更改(甚至重新配置)路由器,它很可能会损坏。

Depending on the router you use, chances are pretty good that you could get it directly from the router. Most of them have a web interface, so it would be a matter of navigating to the correct web page (e.g., "192.168.0.1/whatever") and "scraping" the external IP address from that page. The problem with this is, of course, that it's pretty fragile -- if you change (or even re-configure) your router, chances are pretty good that it'll break.

燕归巢 2024-10-22 18:11:49

您也许可以使用 uPNP,如果失败,则可以回退到whatsmyip.com。

you may be able to use uPNP and fall-back to whatsmyip.com if that fails.

孤星 2024-10-22 18:11:49

如果您担心连接丢失或站点的可用性,您也可以尝试通过包含上述建议来避免该问题。

    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;

希望这也能有所帮助。

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.

冷情 2024-10-22 18:11:49

我这样做:
我创建一个保存地理位置数据的类

[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; }
}

,然后使用以下代码调用地理数据并填充该类。

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;
        }
     }
}

由于答案是“坏”xml,因此需要指定 xRoot 元素,否则会出现错误。

快乐编码

沃尔特

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

止于盛夏 2024-10-22 18:11:49

下面的代码将帮助您获取公共IP地址

    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();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文