Check your internet connection constantly

How can I constantly check the Internet connection in my application and respond if the connection is unavailable?

I am currently using:

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

but he seems rather inelegant.

+5
source share
10 answers

The superuser’s accepted answer to this question describes how Windows can determine if it has network access. You can use a similar method, but I would spawn a separate thread when your application starts, which is responsible for performing the check. Ask a separate thread to check in any way that you think is best, and raise an event if the connection status changes.

+3
source

You are looking for a NetworkAvailabilityChanged event .

To check your internet connection, you can ping a reliable website such as Google.com.

Please note that it is not possible to report every change in your Internet connection (for example, disconnecting your Internet service provider).

+2
source

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, } 
+2
source

if you only need to know if at least one connection is available, you can try the following:

InternetGetConnectedStateEx ()

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

+1
source

if you want to check constantly, use a 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; } } 
+1
source

How do you know if you have an internet connection? Is it enough that you can route packets to the nearest router? Perhaps the machine has only one network adapter, one gateway, and perhaps the connection to the gateway goes down, but the machine can still route to the gateway and local network?

Perhaps the machine has one network adapter and a dozen gateways; perhaps they come and go all the time, but is one of them always up?

What if the machine has several network adapters but only one gateway? Perhaps it can route some subsets of the Internet, but still has an excellent connection to a local network that is not connected to the Internet?

What should I do if multichannel network cards, several gateways are installed on the computer, but for administrative reasons, only parts of the Internet remain?

Do you really care if clients connect to your servers?

What delay between packets is acceptable? (30 ms is good, 300 ms pushes the limits of human endurance, 3,000 ms is unbearably long, 960,000 ms is what it takes to connect to a solar probe.) What packet loss is acceptable?

What are you really trying to measure?

0
source

You can test your internet connection by checking on some website, for example:

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

I know this is an old question, but it 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 an event for the listener, and he constantly checks the connection. this you can add an If statement, for example:

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

This code will save you ... it not only checks the real Internet connection, but also handles an exception with an indication in the console window ... 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(); 
0
source

All Articles