What is the best way to determine if there is a network connection available?
The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).
Here is a piece of code that checks for these cases:
/// <summary> /// Indicates whether any network connection is available /// Filter connections below a specified speed, as well as virtual network cards. /// </summary> /// <returns> /// <c>true</c> if a network connection is available; otherwise, <c>false</c>. /// </returns> public static bool IsNetworkAvailable() { return IsNetworkAvailable(0); } /// <summary> /// Indicates whether any network connection is available. /// Filter connections below a specified speed, as well as virtual network cards. /// </summary> /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param> /// <returns> /// <c>true</c> if a network connection is available; otherwise, <c>false</c>. /// </returns> public static bool IsNetworkAvailable(long minimumSpeed) { if (!NetworkInterface.GetIsNetworkAvailable()) return false; foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { // discard because of standard reasons if ((ni.OperationalStatus != OperationalStatus.Up) || (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) || (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel)) continue; // this allow to filter modems, serial, etc. // I use 10000000 as a minimum speed for most cases if (ni.Speed < minimumSpeed) continue; // discard virtual cards (virtual box, virtual pc, etc.) if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) || (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0)) continue; // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card. if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase)) continue; return true; } return false; }
You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable()
:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With