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

时间:2022-01-30 15:52:20

I have a Windows Forms application. 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.

我有一个Windows窗体应用程序。当用户为我的应用程序导入许可证时,我想“打电话回家”(点击网页上的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?

问题是用户可能没有在那时工作的互联网连接。我想先测试一下。检测用户是否有可用的互联网连接的最佳方法是什么?

7 个解决方案

#1


At a PPOE, at least a hundred thousand dollars was spent on this question. The main sticking points:

在PPOE,至少有十万美元花在这个问题上。主要观点:

  1. A lot of the time, an HTTP connection will go out, and come back with a "200 OK" message. Only it's not your site; it the hotel/cafe/whatever router offering to connect you.

    很多时候,HTTP连接会消失,然后返回“200 OK”消息。只有它不是你的网站;它是酒店/咖啡馆/提供连接你的路由器。

  2. The APIs will lie in interesting and creative ways. 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.

    API将以有趣和创造性的方式存在。例如,如果您曾经拥有调制解调器,但某些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. Made for some seriously grumpy customers.

    在一些(非常重要的)地方,尝试连接将启动连接 - 拨号 - 每分钟充电。再次,在PPOE上他们发布了一个相当受欢迎的软件,它在凌晨3点完成了这项工作。为一些严重脾气暴躁的客户而制造。

  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. Instead they use the Ethernet to emulate a modem (which in turn is set up to emulate an Ethernet +tcp/ip setup). It's called PPPOE and it makes it hard to tell what adapter you are trying to use

    一些主要的互联网服务提供商在宽带上运行时拥有“独特”的软件,他们不够聪明,只能使用他们提供的漂亮的以太网和TCP / IP。相反,他们使用以太网来模拟调制解调器(后者又设置为模拟以太网+ tcp / ip设置)。它被称为PPPOE,它很难分辨你尝试使用的适配器

  5. More and more homes are using DSL and Cabel modems where the computer is "connected", but only to the local box; the local box may have lost connectivity and you won't ever know.

    越来越多的家庭正在使用DSL和Cabel调制解调器,其中计算机是“连接”的,但仅限于本地盒子;本地方框可能已失去连接,你永远不会知道。

THE ONLY SOLUTION is to try a connection AND validate the return.

唯一的解决方案是尝试连接并验证返回。

#2


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

#3


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.

我将看到的唯一合法测试是,是否有任何可用的网络接口,以避免用户在拨号连接时使用拨号提示。

#4


You could throw a ping to the "home" host to see if it returns a reply.

您可以向“home”主机发出ping命令以查看它是否返回了回复。

Net::Ping

#5


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. 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. You can only be sure of that when you actually load the page.

定义'互联网连接'。对我而言,没有“互联网连接”。只有tcp / ip连接,DNS服务器和Web服务器等。你可以做的最好的事情是尝试加载网页,看看它是否有效。正如所建议的那样,您可以尝试ping自己,但这并不意味着Web服务器正在运行,也不意味着可以加载页面。实际加载页面时,您只能确定这一点。

#6


One method that I've used is to create a webservice with a boolean method that always returns "true". Call it from your app, and if you get any exceptions, or "false", you're not connected.

我使用的一种方法是使用一个总是返回“true”的布尔方法创建一个web服务。从您的应用程序中调用它,如果您有任何例外或“假”,则表示您没有连接。

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

#7


When I always needed to check for internet connections in my app I would just ping google.com since it seams to never go down.

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

#1


At a PPOE, at least a hundred thousand dollars was spent on this question. The main sticking points:

在PPOE,至少有十万美元花在这个问题上。主要观点:

  1. A lot of the time, an HTTP connection will go out, and come back with a "200 OK" message. Only it's not your site; it the hotel/cafe/whatever router offering to connect you.

    很多时候,HTTP连接会消失,然后返回“200 OK”消息。只有它不是你的网站;它是酒店/咖啡馆/提供连接你的路由器。

  2. The APIs will lie in interesting and creative ways. 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.

    API将以有趣和创造性的方式存在。例如,如果您曾经拥有调制解调器,但某些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. Made for some seriously grumpy customers.

    在一些(非常重要的)地方,尝试连接将启动连接 - 拨号 - 每分钟充电。再次,在PPOE上他们发布了一个相当受欢迎的软件,它在凌晨3点完成了这项工作。为一些严重脾气暴躁的客户而制造。

  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. Instead they use the Ethernet to emulate a modem (which in turn is set up to emulate an Ethernet +tcp/ip setup). It's called PPPOE and it makes it hard to tell what adapter you are trying to use

    一些主要的互联网服务提供商在宽带上运行时拥有“独特”的软件,他们不够聪明,只能使用他们提供的漂亮的以太网和TCP / IP。相反,他们使用以太网来模拟调制解调器(后者又设置为模拟以太网+ tcp / ip设置)。它被称为PPPOE,它很难分辨你尝试使用的适配器

  5. More and more homes are using DSL and Cabel modems where the computer is "connected", but only to the local box; the local box may have lost connectivity and you won't ever know.

    越来越多的家庭正在使用DSL和Cabel调制解调器,其中计算机是“连接”的,但仅限于本地盒子;本地方框可能已失去连接,你永远不会知道。

THE ONLY SOLUTION is to try a connection AND validate the return.

唯一的解决方案是尝试连接并验证返回。

#2


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

#3


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.

我将看到的唯一合法测试是,是否有任何可用的网络接口,以避免用户在拨号连接时使用拨号提示。

#4


You could throw a ping to the "home" host to see if it returns a reply.

您可以向“home”主机发出ping命令以查看它是否返回了回复。

Net::Ping

#5


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. 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. You can only be sure of that when you actually load the page.

定义'互联网连接'。对我而言,没有“互联网连接”。只有tcp / ip连接,DNS服务器和Web服务器等。你可以做的最好的事情是尝试加载网页,看看它是否有效。正如所建议的那样,您可以尝试ping自己,但这并不意味着Web服务器正在运行,也不意味着可以加载页面。实际加载页面时,您只能确定这一点。

#6


One method that I've used is to create a webservice with a boolean method that always returns "true". Call it from your app, and if you get any exceptions, or "false", you're not connected.

我使用的一种方法是使用一个总是返回“true”的布尔方法创建一个web服务。从您的应用程序中调用它,如果您有任何例外或“假”,则表示您没有连接。

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

#7


When I always needed to check for internet connections in my app I would just ping google.com since it seams to never go down.

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