The ping command is used to judge the network, but this is too bad and the delay is long. So I checked it online, it can be determined by calling two dynamic connection libraries that come with Windows API.
1. wininet. dll
2. sensapi. dll
Let's talk about the first one first:
Wininet. dll can call the internetgetconnectedstate Method
Sensapi. dll can call the isnetworkalive Method
To use these two methods, you must first introduce the dynamic Connection Library,
You need to reference the namespace using system. runtime. interopservices;
The Code is as follows:
Method 1:
// Introduce API functions
[Dllimport ("wininet. dll")]
Public static extern bool internetgetconnectedstate (out long lpdwflags, long dwreserved );
Public String judgeonline ()
{
Int internet_connection_modem = 1;
Int internet_connection_lan = 2;
Int internet_connection_proxy = 4;
Int internet_connection_modem_busy = 8;
Int internet_connection_offline = 32;
Long lfag;
String resultstr = "";
If (internetgetconnectedstate (Out lfag, 0 ))
Resultstr = "the network connection is normal! ";
Else
Resultstr = "network connection unavailable! ";
If (lfag & internet_connection_offline)> 0)
Resultstr + = "offline local system is in offline mode. ";
If (lfag & internet_connection_modem)> 0)
Resultstr + = "modem local system uses a modem to connect to the Internet. ";
If (lfag & internet_connection_lan)> 0)
Resultstr + = "the LAN used by the LAN Local system is connected to the Internet. ";
If (lfag & internet_connection_proxy)> 0)
Resultstr + = "a proxy ";
If (lfag & internet_connection_modem_busy)> 0)
Resultstr + = "modem but modem is busy ";
Return resultstr;
}
Method 2:
[Dllimport ("sensapi. dll")]
Private extern static bool isnetworkalive (Out int connectiondescription );
Private string fun_isnetworkalive ()
{
Int network_alive_lan = 0;
Int network_alive_wan = 2;
Int network_alive_aol = 4;
String output = NULL;
// Internet Access Method
Int flags;
// Online or not
Bool m_bonline = true;
M_bonline = isnetworkalive (out flags );
// Online
If (m_bonline)
{
If (flags & network_alive_lan) = network_alive_lan)
{
Output = "online: Lan ";
}
If (flags & network_alive_wan) = network_alive_wan)
{
Output = "online: Wan ";
}
If (flags & network_alive_aol) = network_alive_aol)
{
Output = "online: AOL ";
}
}
Else
{
Output = "offline: noonline ";
}
Return output;
}
Note: after testing, both methods can be used, but the first method still has latency. We recommend that you use the second method for timely response.