TOC
Work with My
namespace
We can use My.Computer.Network.IsAvailable in Visual Basic.NET to determine whether the network is connected. The definition of this property is:
153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
'''********************************************************************** ''';IsAvailable ''' <summary> ''' Indicates whether or not the local machine is connected to an IP network. ''' </summary> ''' <value>True if connected, otherwise False</value> ''' <remarks></remarks> Public ReadOnly Property IsAvailable() As Boolean Get Return NetInfoAlias.NetworkInterface.GetIsNetworkAvailable() End Get End Property |
It leads to the approach in C#.
Using NetworkInterface
class
We can also use System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable
static function to achieve the same goal.
The function is described in MSDN as follows:
A network connection is considered to be available if any network interface is marked “up” and is not a loopback or tunnel interface.
Using InternetGetConnectedState
API
A function exposed from Wininet.dll can be used to query network connectivity info. Detialed information is here: InternetGetConnectedState function。The definition of this function is
1 2 3 4 |
BOOL InternetGetConnectedState( _Out_ LPDWORD lpdwFlags, _In_ DWORD dwReserved ); |
It returns TRUE
if there exist available internet connections. Thus we can compose the following code in C# to check it out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Runtime.InteropServices; namespace ConsoleApplication2 { class Program { [Flags] public enum INTERNET_CONNECTION : int { MODEM = 0x01, LAN = 0x02, PROXY = 0x04, MODEM_BUSY = 0x08, RAS_INSTALLED = 0x10, OFFLINE = 0x20, CONFIGURED = 0x40, } [DllImport("winInet")] private static extern bool InternetGetConnectedState(out INTERNET_CONNECTION dwFlag, int dwReserved); static void Main(string[] args) { INTERNET_CONNECTION flag; if (InternetGetConnectedState(out flag, 0)) Console.WriteLine("Network connected: {0}。", flag); else Console.WriteLine("Network disconnected."); } } } |
Using Ping
We can also determine whether the machine is online by executing ping test to specific sites. Its advantage lies in that if the result is yes, then we can be 100% sure the network is available.
This method can be implemented by using System.Net.NetworkInformation.Ping
. You can consult MSDN to learn how to realize it.