当前位置:首页 > 行业动态 > 正文

c# 判断网络是否已断开连接

csharp,bool isConnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();,

在C#中,判断网络是否已断开连接是一个常见的需求,尤其是在开发网络应用程序时,以下是一些常用的方法和步骤来判断网络连接状态:

一、使用Ping类

1、发送ICMP回显请求

原理Ping类用于向指定的主机发送ICMP回显请求消息,并等待响应,如果收到响应,则说明网络连接正常;如果超时或无法到达目标主机,则可能表示网络已断开连接。

示例代码

 using System;
     using System.Net;
     using System.Net.NetworkInformation;
     class Program
     {
         static void Main()
         {
             string host = "www.example.com";
             Ping pingSender = new Ping();
             PingOptions options = new PingOptions();
             PingReply reply = pingSender.Send(IPAddress.Parse(host), 3000, options);
             if (reply.Status == IPStatus.Success)
             {
                 Console.WriteLine("网络连接正常");
             }
             else
             {
                 Console.WriteLine("网络已断开连接");
             }
         }
     }

注意事项:需要捕获异常,例如当目标主机不存在或网络不可达时,可能会抛出异常,某些网络环境可能阻止ICMP请求,导致无法准确判断网络状态。

2、处理PingCompleted事件

原理:通过异步方式发送Ping请求,并在PingCompleted事件中处理响应,避免阻塞主线程。

示例代码

 using System;
     using System.Net;
     using System.Net.NetworkInformation;
     class Program
     {
         static void Main()
         {
             string host = "www.example.com";
             Ping pingSender = new Ping();
             PingOptions options = new PingOptions();
             pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
             try
             {
                 pingSender.SendAsync(IPAddress.Parse(host), 3000, options, null);
             }
             catch (Exception ex)
             {
                 Console.WriteLine("网络已断开连接: " + ex.Message);
             }
             Console.ReadLine();
         }
         private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
         {
             if (e.Reply.Status == IPStatus.Success)
             {
                 Console.WriteLine("网络连接正常");
             }
             else
             {
                 Console.WriteLine("网络已断开连接");
             }
         }
     }

注意事项:同样需要注意异常处理和网络环境对ICMP请求的限制。

c# 判断网络是否已断开连接

二、检查网络接口状态

1、获取网络接口信息

原理:通过NetworkInterface类获取本地计算机的网络接口列表,并检查每个接口的状态,如果所有接口都处于断开状态,则可以认为网络已断开连接。

示例代码

 using System;
     using System.Net.NetworkInformation;
     class Program
     {
         static void Main()
         {
             NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
             bool isConnected = false;
             foreach (NetworkInterface ni in interfaces)
             {
                 if (ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                 {
                     isConnected = true;
                     break;
                 }
             }
             if (isConnected)
             {
                 Console.WriteLine("网络连接正常");
             }
             else
             {
                 Console.WriteLine("网络已断开连接");
             }
         }
     }

注意事项:此方法只能检测本地网络接口的状态,不能确定与外部网络的连接情况,即使本地网络接口处于启用状态,但路由器或ISP出现问题,仍然可能导致无法访问互联网。

2、检查特定的网络接口

原理:如果只关心某个特定的网络接口(例如以太网接口),可以指定该接口的名称进行检查。

c# 判断网络是否已断开连接

示例代码

 using System;
     using System.Net.NetworkInformation;
     class Program
     {
         static void Main()
         {
             string interfaceName = "以太网"; // 替换为实际的网络接口名称
             NetworkInterface ni = NetworkInterface.GetAllNetworkInterfaces().Where(n => n.Name == interfaceName).FirstOrDefault();
             if (ni != null && ni.OperationalStatus == OperationalStatus.Up)
             {
                 Console.WriteLine("网络连接正常");
             }
             else
             {
                 Console.WriteLine("网络已断开连接");
             }
         }
     }

注意事项:需要确保指定的网络接口名称正确,并且该接口存在于本地计算机上,否则,可能会导致NullReferenceException异常。

三、尝试建立TCP连接

1、同步方式

原理:尝试与一个已知的服务器端口建立TCP连接,如果连接成功,则说明网络连接正常;如果连接失败,则可能表示网络已断开连接。

示例代码

 using System;
     using System.Net;
     using System.Net.Sockets;
     using System.Threading;
     class Program
     {
         static void Main()
         {
             string host = "www.example.com";
             int port = 80; // HTTP端口号
             TcpClient client = new TcpClient();
             try
             {
                 client.Connect(host, port);
                 Console.WriteLine("网络连接正常");
             }
             catch (SocketException ex)
             {
                 Console.WriteLine("网络已断开连接: " + ex.Message);
             }
             finally
             {
                 client.Close();
             }
         }
     }

注意事项:选择合适的服务器和端口很重要,通常可以选择一些知名的网站或服务,需要处理异常情况,例如目标服务器不可达、端口被占用等。

c# 判断网络是否已断开连接

2、异步方式

原理:使用异步方法尝试建立TCP连接,提高程序的响应性。

示例代码

 using System;
     using System.Net;
     using System.Net.Sockets;
     using System.Threading;
     using System.Threading.Tasks;
     class Program
     {
         static async Task Main()
         {
             string host = "www.example.com";
             int port = 80; // HTTP端口号
             TcpClient client = new TcpClient();
             try
             {
                 await client.ConnectAsync(host, port);
                 Console.WriteLine("网络连接正常");
             }
             catch (SocketException ex)
             {
                 Console.WriteLine("网络已断开连接: " + ex.Message);
             }
             finally
             {
                 client.Close();
             }
         }
     }

注意事项:异步操作需要在支持异步编程的环境中使用,例如在ASP .NET Core或其他异步框架中,要注意正确处理任务的取消和异常情况。

在C#中判断网络是否已断开连接有多种方法,每种方法都有其优缺点和适用场景,开发人员可以根据具体的需求和应用场景选择合适的方法来实现网络状态的检测,为了提高判断的准确性和可靠性,可以结合多种方法进行综合判断。