如何在C#中使用Win App检测静态IP [英] How to detect static ip using win app in c#

查看:76
本文介绍了如何在C#中使用Win App检测静态IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我错了,请纠正我. IP有两种类型- 第一,我们分配给LAN卡的静态(固定)IP地址,第二,我们从服务提供商那里收到的地址.

Please correct me if i am wrong. There are two types of IP - One, the static(fixed) IP address we assign to the LAN card and second that we received from the service provider.

例如我的机器设置的IP地址为192.168.1.10,而ISP提供的IP地址为218.64.xx.xx. (您可以使用 http://www.ip2location.com/进行检查)

For ex. The IP address set for my machine is 192.168.1.10 while the IP address given by ISP is 218.64.xx.xx. (You can check this using http://www.ip2location.com/)

当我使用ASP.net时,我可以使用-获得ISP提供的IP地址. HttpContext.Current.Request.UserHostAddress;

When I use ASP.net, i can get the IP address provided by ISP using - HttpContext.Current.Request.UserHostAddress;

问题: 现在,我正在Windows Forms环境中工作,但是虽然能够获得固定IP,但是却无法获得ISP提供的IP.

The Problem: Now, I am working in Windows Forms environment but unable to get the IP provided by ISP, though I am able to get the fixed IP.

有人可以帮助我吗?

感谢分享您的时间.

推荐答案

您正在尝试获取路由器的外部IP地址.

You're trying to get the external IP address of your router.

您需要将HTTP请求发送到第三方服务,该服务将使用IP地址进行回复.

You need to send an HTTP request to a third-party service which will reply with the IP address.

您可以使用WebClient类来做到这一点.

You can do that using the WebClient class.

例如:

///<summary>Gets the computer's external IP address from the internet.</summary>
static IPAddress GetExternalAddress() {
    //<html><head><title>Current IP Check</title></head><body>Current IP Address: 129.98.193.226</body></html>
    var html = new WebClient().DownloadString("http://checkip.dyndns.com/");

    var ipStart = html.IndexOf(": ", StringComparison.OrdinalIgnoreCase) + 2;
    return IPAddress.Parse(html.Substring(ipStart, html.IndexOf("</", ipStart, StringComparison.OrdinalIgnoreCase) - ipStart));
}

这篇关于如何在C#中使用Win App检测静态IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆