不断检查互联网连接

时间:2011-06-26 03:27:28

标签: c# .net internet-connection

如何在我的应用程序中不断检查互联网连接,并在连接不可用时作出响应?

目前我正在使用:

while(true) {
 if(HasConnection()) {
     //doSomething..
  }
   //stop app by 1sec
}

但似乎相当不优雅。

11 个答案:

答案 0 :(得分:3)

超级用户对this question的接受回答描述了Windows确定其是否具有网络访问权限的方式。您可以使用类似的方法,但是当您的应用程序启动时,我会生成一个单独的线程负责进行检查。让单独的线程以您认为最好的方式执行检查,并在连接状态发生变化时引发事件。

答案 1 :(得分:2)

您正在寻找NetworkAvailabilityChanged event

要检查互联网连接,您可以ping建立一个可靠的网站,例如Google.com。

请注意,无法通知互联网连接中的每次更改(例如ISP中断)。

答案 2 :(得分:2)

使用以下代码:

public static class LocalSystemConnection
{
    [DllImport("wininet.dll", SetLastError=true, CallingConvention = CallingConvention.ThisCall)]
    extern static bool InternetGetConnectedState(out ConnectionStates lpdwFlags, long dwReserved);

    /// <summary>
    /// Retrieves the connected state of the local system.
    /// </summary>
    /// <param name="connectionStates">A <see cref="ConnectionStates"/> value that receives the connection description.</param>
    /// <returns>
    /// A return value of true indicates that either the modem connection is active, or a LAN connection is active and a proxy is properly configured for the LAN.
    /// A return value of false indicates that neither the modem nor the LAN is connected.
    /// If false is returned, the <see cref="ConnectionStates.Configured"/> flag may be set to indicate that autodial is configured to "always dial" but is not currently active.
    /// If autodial is not configured, the function returns false.
    /// </returns>
    public static bool IsConnectedToInternet(out ConnectionStates connectionStates)
    {
        connectionStates = ConnectionStates.Unknown;
        return InternetGetConnectedState(out connectionStates, 0);
    }

    /// <summary>
    /// Retrieves the connected state of the local system.
    /// </summary>
    /// <returns>
    /// A return value of true indicates that either the modem connection is active, or a LAN connection is active and a proxy is properly configured for the LAN.
    /// A return value of false indicates that neither the modem nor the LAN is connected.
    /// If false is returned, the <see cref="ConnectionStates.Configured"/> flag may be set to indicate that autodial is configured to "always dial" but is not currently active.
    /// If autodial is not configured, the function returns false.
    /// </returns>
    public static bool IsConnectedToInternet()
    {
        ConnectionStates state = ConnectionStates.Unknown;
        return IsConnectedToInternet(out state);
    }
}

[Flags]
public enum ConnectionStates
{
    /// <summary>
    /// Unknown state.
    /// </summary>
    Unknown = 0,

    /// <summary>
    /// Local system uses a modem to connect to the Internet.
    /// </summary>
    Modem = 0x1,

    /// <summary>
    /// Local system uses a local area network to connect to the Internet.
    /// </summary>
    LAN = 0x2,

    /// <summary>
    /// Local system uses a proxy server to connect to the Internet.
    /// </summary>
    Proxy = 0x4,

    /// <summary>
    /// Local system has RAS (Remote Access Services) installed.
    /// </summary>
    RasInstalled = 0x10,

    /// <summary>
    /// Local system is in offline mode.
    /// </summary>
    Offline = 0x20,

    /// <summary>
    /// Local system has a valid connection to the Internet, but it might or might not be currently connected.
    /// </summary>
    Configured = 0x40,
}

答案 3 :(得分:1)

如果您只需要知道是否有至少一个连接可用,您可以尝试:

InternetGetConnectedStateEx()

http://msdn.microsoft.com/en-us/library/aa384705%28v=vs.85%29.aspx

答案 4 :(得分:1)

  

如果您要连续检查,请使用计时器

    private Timer timer1;
    public void InitTimer()
    {
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timerEvent);
        timer1.Interval = 2000; // in miliseconds
        timer1.Start();
    }

    private void timerEvent(object sender, EventArgs e)
    {
        DoSomeThingWithInternet();
    }

     private void DoSomeThingWithInternet()
    {
        if (isConnected())
        {
           // inform user that "you're connected to internet"
        }
        else
        {
             // inform user that "you're not connected to internet"
        }
    }

    public static bool isConnected()
    {
        try
        {
            using (var client = new WebClient())
            using (client.OpenRead("http://clients3.google.com/generate_204"))
            {
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

答案 5 :(得分:0)

您如何知道自己是否有互联网连接?您是否可以将数据包路由到附近的路由器?也许机器只有一个网卡,一个网关,也许网关的连接断开但机器仍然可以路由到网关和本地网络?

也许机器有一个网卡和十几个网关;也许他们总是来去匆匆,但一个总是在吗?

如果机器有多个NIC但只有一个网关怎么办?也许它可以路由到互联网的某个子集,但仍然可以很好地连接到未连接到互联网的本地网络?

如果机器有多个网卡,多个网关,但出于管理政策的原因,仍然只有部分互联网是可路由的,该怎么办?

您是否真的只关心客户是否可以连接您的服务器?

数据包之间可以接受哪种延迟? (30ms是好的,300ms正在推动人类耐力的极限,3000ms是无法忍受的长时间,960000ms是连接到太阳探测器所需的。)可以接受什么样的丢包?

真正试图测量什么?

答案 6 :(得分:0)

This将是一个开始,但正如sarnold所提到的,你需要考虑很多事情

答案 7 :(得分:0)

您可以通过ping某个网站来测试互联网连接:

    public bool IsConnectedToInternet
    {
        try
        {
            using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping())
            {
                string address = @"http://www.google.com";//                        System.Net.NetworkInformation.PingReply pingReplay = ping.Send(address);//you can specify timeout.
                if (pingReplay.Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    return true;
                }
             }
        }
        catch
        {
#if DEBUG
            System.Diagnostics.Debugger.Break();
#endif//DEBUG
        }

        return false;
    }

答案 8 :(得分:0)

我知道这是一个老问题,但这对我来说很有用。

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;

private async void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
        {
            //code to execute...
        }

我将事件订阅给侦听器,并且它会不断检查连接。您可以添加一个If语句,例如:

if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
   {
        //Send Ping...
   }
else
    {
        //other code....
    }

答案 9 :(得分:0)

此代码将为您挽救生命。.它不仅检查真实的Internet连接,还可以在控制台窗口中指示异常,从而处理异常... 每2秒

using System;
using System.Net;
using System.Threading;
using System.Net.Http;

bool check() //Checking for Internet Connection 
            {
                while (true)
                {
                    try
                    { var i = new Ping().Send("www.google.com").Status;
                        if (i == IPStatus.Success)
                        { Console.WriteLine("connected");
                            return true;
                        }
                        else { return false; }
                        }

                    catch (Exception)
                    {
                        Console.WriteLine("Not Connected");
                        Thread.Sleep(2000);
                        continue;
                    }
                }

            };
            check();

答案 10 :(得分:0)

使用NetworkChange.NetworkAvailabilityChanged是最容易引起误解的答案。它检查网络可用性更改而不是Internet连接更改。

我们可以使用Windows NLM API监视互联网连接。

using System;
using System.Runtime.InteropServices.ComTypes;
using NETWORKLIST;

namespace Components.Network.Helpers
{
    public class InternetConnectionChecker : INetworkListManagerEvents, IDisposable
    {
        private int _cookie;
        private IConnectionPoint _connectionPoint;
        private readonly INetworkListManager _networkListManager;

        public InternetConnectionChecker()
        {
            _networkListManager = new NetworkListManager();
        }

        public bool IsConnected()
        {
            return _networkListManager.IsConnectedToInternet;
        }

        public void StartMonitoringConnection()
        {
            try
            {
                var container = _networkListManager as IConnectionPointContainer;
                if (container == null)
                    throw new Exception("connection container is null");
                var riid = typeof(INetworkListManagerEvents).GUID;
                container.FindConnectionPoint(ref riid, out _connectionPoint);
                _connectionPoint.Advise(this, out _cookie);
            }
            catch (Exception e)
            {

            }
        }

        public void ConnectivityChanged(NLM_CONNECTIVITY newConnectivity)
        {
            if (_networkListManager.IsConnectedToInternet)
            {
                // do something based on internet connectivity
            }

        }

        public void Dispose()
        {
            _connectionPoint.Unadvise(_cookie);
        }
    }
}