Two ways to check whether the network is connected in C #

Source: Internet
Author: User

Using System;
2 using System.Collections.Generic;
3 using System.Text;
4//Method one
5 using System.Runtime;
6 using System.Runtime.InteropServices;
7//Method two Net2.0 new class library
8 using System.Net.NetworkInformation;
9
Ten namespace Internetcheck
11 {
public class Internet
13 {
[DllImport ("Wininet.dll")]
The private extern static bool InternetGetConnectedState (int Description, int reservedvalue);
16
#region Method One
//<summary>
19///For checking whether the network can connect to the Internet, True indicates a successful connection, false indicates a connection failure
</summary>
///<returns></returns>
public static bool Isconnectinternet ()
23 {
Description int = 0;
Return InternetGetConnectedState (Description, 0);
26}
#endregion
28
#region Method Two
<summary>
31///To check whether the IP address or domain name can be accessed using the TCP/IP protocol (using the ping command), True indicates Ping succeeded, false indicates Ping failed
</summary>
//<param Name= "stripordname" > Input parameters, indicating IP address or domain name </param>
<returns></returns>
public static bool Pingipordomainname (string stripordname)
36 {
PNS Try
38 {
Objpingsender ping = new ping ();
PingOptions objpinoptions = new PingOptions ();
Objpinoptions.dontfragment = true;
The String data = "";
byte[] buffer = Encoding.UTF8.GetBytes (data);
inttimeout int = 120;
Pingreply objpinreply = Objpingsender.send (stripordname, inttimeout, buffer, objpinoptions);
Strinfo string = objPinReply.Status.ToString ();
if (Strinfo = = "Success")
48 {
The return true;
50}
Or else
52 {
The return is false;
54}
55}
Exception catch ()
57 {
The "+" return false;
59}
60}
#endregion
62}
63}

Two ways to check whether the network is connected in C #

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.