C # Check whether the network is connected
There are several ways to check the Internet to see if the network is connected, tested, the first way is affected by the ping delay, in some do not support ping address or network segment is not even available, so recommended Method 2
1. Call the ping command in cmd, analyze the output information to determine whether the network is connected
Use the ping command to determine that the Txtip text box enters a valid remote host IP
System.Diagnostics.Process proip=new System.Diagnostics.Process ();
Proip.startinfo.filename= "cmd.exe";
ProIP.StartInfo.UseShellExecute = false;
ProIP.StartInfo.RedirectStandardInput = true;
ProIP.StartInfo.RedirectStandardOutput = true;
ProIP.StartInfo.RedirectStandardError = true;
ProIP.StartInfo.CreateNoWindow = true;//does not display cmd window
Proip.start ();
ProIP.StandardInput.WriteLine ("ping" +this.txtip.text.trim ());
ProIP.StandardInput.WriteLine ("Exit");
String Strresult=proip.standardoutput.readtoend ();
if (Strresult.indexof (0% loss))!=-1)
This.txtshow.text= "Ping through." ";
else if (Strresult.indexof (100% loss))!=-1)
This.txtshow.text= "Could not Ping. ";
Else
this.txtshow.text= "Data is missing. "
Proip.close ();
2. Use the InternetGetConnectedState () function
This Win32 API in the system System32 folder WinInet.dll, can be used to determine whether the network and the Internet is the way the Modem or LAN, etc.
To import namespaces using DllImport
Using System.Runtime.InteropServices;
The meaning of the status identification bit returned by InternetGetConnectedState:
Private Const int INTERNET_CONNECTION_MODEM = 1;
Private Const int Internet_connection_lan = 2;
Private Const int internet_connection_proxy = 4;
Private Const int INTERNET_CONNECTION_MODEM_BUSY = 8;
[DllImport ("WinInet.dll")]
To declare an external function:
private static extern bool InternetGetConnectedState (
ref int Dwflag,
int dwreserved
);
static void Main (string[] args)
{
int dwflag = 0;
String netstatus = "";
if (! InternetGetConnectedState (ref dwflag, 0))
Console.WriteLine ("Not networked.") ");
Else
{
if ((Dwflag & Internet_connection_modem)!= 0)
Netstatus + + "Use of modulating demodulator internet/n";
if ((Dwflag & Internet_connection_lan)!= 0)
Netstatus + = "Use network card internet/n";
if ((Dwflag & Internet_connection_proxy)!= 0)
Netstatus + + "using proxy internet/n";
if ((Dwflag & Internet_connection_modem_busy)!= 0)
Netstatus + = "Modem is occupied by other non-Internet connections/n";
}
Console.WriteLine (Netstatus);
Console.ReadLine ();
}