Check for internet connection constantly

此生再无相见时 提交于 2020-01-03 14:28:22

问题


How can I check for an internet connection constantly in my application and respond if the connection is not available?

Currently I am using:

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

but it seems rather inelegant.


回答1:


The accepted answer to this question on superuser describes the way the Windows determines if it has network access. You could use a similar method, but I would spawn a separate thread when your application starts that is responsible for doing the check. Have the separate thread perform the check in whatever manner you feel is the best and raise an event if the connection status changes.




回答2:


You're looking for the NetworkAvailabilityChanged event.

To check for internet connectivity, you can ping a reliable website, such as Google.com.

Note that it is not possible to be notified of every change in internet connectivity (such as an ISP outage).




回答3:


Use the following code:

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,
}



回答4:


if you only need to know if at least one connection is available you can try this:

InternetGetConnectedStateEx()

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




回答5:


if you want to check continuously then use timer

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



回答6:


How will you know if you have an Internet Connection? Is it enough that you can route packets to a nearby router? Maybe the machine has only a single NIC, a single gateway, and perhaps that Gateway's connection goes down but the machine can still route to the gateway and local network?

Maybe the machine has a single NIC and a dozen gateways; maybe they come and go all the time, but one of them is always up?

What if the machine has multiple NICs, but only a single gateway? Perhaps it can route to some subset of the Internet, but still has an excellent connection to a local network not connected to the Internet?

What if the machine has muliple NICs, multiple gateways, but for administrative policy reasons, still only portions of the Internet are routeble?

Do you really only care if clients have connectivity to your servers?

What kind of latency between packets is acceptable? (30ms is good, 300ms is pushing the limits of human endurance, 3000ms is intolerable long time, 960000ms is what would be required for a connection to a solar probe.) What kind of packet loss is acceptable?

What are you really trying to measure?




回答7:


This would be a start but as sarnold has mentioned there are a lot of things you need to consider




回答8:


You can test internet connectivity by pinging to some website like:

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



回答9:


I know this is an old question but this works great for me.

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

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

I subscribe to the event to a listener and it constantly checks for connection. this you can add a If statement such as:

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



回答10:


This code will life-saving for you.. it not only checks real internet connection but also handle the exception with indication on the console window... after every 2 seconds

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


来源:https://stackoverflow.com/questions/6481957/check-for-internet-connection-constantly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!