Winform determines whether the network is connected to the C # version of the network. How can we use C # To determine whether the network is connected? There are more than n methods. We will try to explain them as completely as possible below.
The first method is the simplest, but not accurate.
Private void btnisconnect_click (Object sender, eventargs E)
{
If (systeminformation. Network ){
MessageBox. Show ("connected, but not sure whether it is Internet or LAN ");
}
}
This method is also true under the LAN
The second method is to Ping An address, so we will adopt Baidu. If Baidu is down, wow, it will not blame anyone. Haha
First, reference the namespace
Using system. net. networkinformation;
Then, let's simply implement it. This kind of implementation is not perfect, and we are gradually improving it,
Private void btnping_click (Object sender, eventargs E)
{
Ping = new Ping ();
Pingreply Pr = ping. Send ("Baidu.com ");
If (PR. Status = ipstatus. Success)
MessageBox. Show ("network status ");
Else
MessageBox. Show ("your network cable has fallen ");
}
Ping. Send ("Baidu.com ");
Remember that sending has eight overload methods. You can adjust them by yourself. Let's get a Google IP address first.
Then let's start. Here we mainly prepare our data based on the send parameter. Some people also refer to this as a heartbeat packet. In other words, they are constantly sending requests to determine whether they are connected to the Internet.
Ping = new Ping ();
Pingoptions poptions = new pingoptions ();
Poptions. dontfragment = true;
String data = string. empty;
Byte [] buffer = encoding. ASCII. getbytes (data );
Prepare data in place and start sending