Winform determines whether the network is connected to the C # network connection

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.