简体   繁体   English

使用.NET检测互联网连接的最佳方法是什么?

[英]What's the best way to detect an internet connection using .NET?

I have a Windows Forms application. 我有一个Windows窗体应用程序。 When the user imports a license for my application I'd like to "phone home" (hit an aspx page on the web) and register the license information. 当用户为我的应用程序导入许可证时,我想“打电话回家”(点击网页上的aspx页面)并注册许可证信息。

The problem is that the user may not have an internet connection working at that moment. 问题是用户可能没有在那时工作的互联网连接。 I'd like to test this first. 我想先测试一下。 What's the best way to detect if the user has an internet connection available? 检测用户是否有可用的互联网连接的最佳方法是什么?

At a PPOE, at least a hundred thousand dollars was spent on this question. 在PPOE,至少有十万美元花在这个问题上。 The main sticking points: 主要观点:

  1. A lot of the time, an HTTP connection will go out, and come back with a "200 OK" message. 很多时候,HTTP连接会消失,然后返回“200 OK”消息。 Only it's not your site; 只有它不是你的网站; it the hotel/cafe/whatever router offering to connect you. 它是酒店/咖啡馆/提供连接你的路由器。

  2. The APIs will lie in interesting and creative ways. API将以有趣和创造性的方式存在。 For example, some of the Windows network APIs return bad connection data if you used to have a modem, but then upgraded to DSL, but didn't run the wizard. 例如,如果您曾经拥有调制解调器,但某些Windows网络API会返回错误的连接数据,但随后升级到DSL,但未运行向导。

  3. In some (very important) places, trying to connect will start a connection -- on dialup -- with a per-minute charge. 在一些(非常重要的)地方,尝试连接将启动连接 - 拨号 - 每分钟充电。 Again, at the PPOE they shipped a reasonably popular bit of software that did this at 3:00 AM. 再次,在PPOE上他们发布了一个相当受欢迎的软件,它在凌晨3点完成了这项工作。 Made for some seriously grumpy customers. 为一些严重脾气暴躁的客户而制造。

  4. Some major ISPs have "unique" software when run on broadband where they weren't clever enough to just use the nice Ethernet and TCP/IP they are given. 一些主要的互联网服务提供商在宽带上运行时拥有“独特”的软件,他们不够聪明,只能使用他们提供的漂亮的以太网和TCP / IP。 Instead they use the Ethernet to emulate a modem (which in turn is set up to emulate an Ethernet +tcp/ip setup). 相反,他们使用以太网来模拟调制解调器(后者又设置为模拟以太网+ tcp / ip设置)。 It's called PPPOE and it makes it hard to tell what adapter you are trying to use 它被称为PPPOE,它很难分辨你尝试使用的适配器

  5. More and more homes are using DSL and Cabel modems where the computer is "connected", but only to the local box; 越来越多的家庭使用DSL和Cabel调制解调器,其中计算机是“连接”的,但仅限于本地盒子; the local box may have lost connectivity and you won't ever know. 本地方框可能已失去连接,你永远不会知道。

THE ONLY SOLUTION is to try a connection AND validate the return. 唯一的解决方案是尝试连接并验证返回。

Check the WebRequest.GetResponse Method 检查WebRequest.GetResponse方法

// Create a new WebRequest Object to the mentioned URL.
WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");
Console.WriteLine("\nThe Timeout time of the request before setting is : {0} milliseconds",myWebRequest.Timeout);

// Set the 'Timeout' property in Milliseconds.
myWebRequest.Timeout=10000;

// This request will throw a WebException if it reaches the timeout limit before it is able to fetch the resource.
WebResponse myWebResponse=myWebRequest.GetResponse();

or you could call the InternetGetConnectedState API 或者您可以调用InternetGetConnectedState API

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue ) ;

public static bool IsConnectedToInternet()
{
    int Desc ;
    return InternetGetConnectedState(out Desc, 0);
}

I don't see any advantage in testing if the connection is available before performing the request. 在执行请求之前,我没有看到测试连接是否可用的任何优势。 The connection could still go down after you checked, and there is no reliable way of telling if you request would work before you try it. 检查后连接仍然可能会断开,并且在尝试之前没有可靠的方法来告知您的请求是否有效。 I also don't see any advantage for the user. 我也没有看到用户的任何优势。

The only legitimate test I would see is if there are any available network interfaces, to avoid anoying the user with a dial-up prompt in case he/she is still on dial-up connection. 我将看到的唯一合法测试是,是否有任何可用的网络接口,以避免用户使用拨号提示,以防他/她仍在拨号连接。

You could throw a ping to the "home" host to see if it returns a reply. 您可以向“home”主机发出ping命令以查看它是否返回了回复。

Net::Ping 网::平

Define 'internet connection'. 定义'互联网连接'。 To me there is no 'internet connection'. 对我来说,没有'互联网连接'。 There are just tcp/ip connections, dns servers and web servers, etc. The best you can do is try to load the webpage and see if it works. 只有tcp / ip连接,DNS服务器和Web服务器等。您可以做的最好的事情是尝试加载网页,看看它是否有效。 As suggested you could try to ping yourself, but that does not mean the web server is running nor that the page can be loaded. 正如所建议的那样,您可以尝试ping自己,但这并不意味着Web服务器正在运行,也不意味着可以加载页面。 You can only be sure of that when you actually load the page. 实际加载页面时,您只能确定这一点。

One method that I've used is to create a webservice with a boolean method that always returns "true". 我使用的一种方法是使用一个总是返回“true”的布尔方法创建一个web服务。 Call it from your app, and if you get any exceptions, or "false", you're not connected. 从您的应用程序中调用它,如果您有任何例外或“假”,则表示您没有连接。

    [WebMethod]
    public bool IsAvailable()
    {
        return true;
    }

and call it: 并称之为:

        private bool IsOnline()
        {
            Cursor = Cursors.WaitCursor;
            var proxy = new WS();
            bool IsOnline = false;
            try
            {
                IsOnline = proxy.IsAvailable();
            }
            catch (System.Net.WebException WebEx)
            {
                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("WebException Status", WebEx.Status.ToString());
                if (WebEx.Status == System.Net.WebExceptionStatus.ProtocolError)
                {
                    nvc.Add("Status Code", ((System.Net.HttpWebResponse)WebEx.Response).StatusCode.ToString());
                    nvc.Add("Status Description", ((System.Net.HttpWebResponse)WebEx.Response).StatusDescription);
                }
                ExceptionManager.Publish(WebEx, nvc);
            }
            catch (Exception)
            {
                IsOnline = false;
            }
            Cursor = Cursors.Default;
            return IsOnline;
        }

当我总是需要检查我的应用程序中的互联网连接时,我会ping google.com,因为它接缝永不停机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 .NET 检查 Inte.net 连接的最佳方法是什么? - What is the best way to check for Internet connectivity using .NET? 熟悉.NET - 最好的方法是什么? - Getting familiar with .NET - What's the best way? 在 .NET DLL 中存储连接字符串的最佳方法是什么? - What is the best way to store connection string in .NET DLLs? 为.Net应用程序实施防篡改的最佳想法是什么 - What's the Best idea to implement an Anti Connection Tampering for .Net application 使用.Net Assembly中的公钥令牌保护产品免遭破解的最佳方法是什么? - What 's the best way to protect product from cracking by using Public key token in .Net Assembly? 使用vb.net在大型excel文件上执行SQL查询的最佳方法是什么? - What's the best way to execute SQL Query on large excel file using vb.net? .NET winforms应用程序在不使用ClickOnce的情况下更新自身的最佳方法是什么? - What's the best way for a .NET winforms application to update itself without using ClickOnce? 将.Net类转换为SQLite表的最佳方法是什么? - What's the best way to turn a .Net class into a SQLite table? 在.NET中,同一台机器中的两个进程进行通信的最佳方法是什么? - In .NET what's the best way for two processes in the same machine to communicate? 在.net中设置Windows服务描述的最佳方法是什么 - What's the best way to set a windows service description in .net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM