如何在c#中使用win app检测静态ip

Irf*_*aza 1 c# ip-address winforms

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

对于前者 为我的机器设置的IP地址是192.168.1.10,而ISP给出的IP地址是218.64.xx.xx. (您可以使用http://www.ip2location.com/查看此内容)

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

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

有谁能够帮我?

谢谢你分享你的时间.

SLa*_*aks 9

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

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

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

例如:

///<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));
}
Run Code Online (Sandbox Code Playgroud)