.NET 检测地址/主机/域名是否正常

🌱PING 地址/主机名/域名

cs 复制代码
     /// <summary>
     /// PING
     /// </summary>
     /// <param name="ip">ip</param>
     /// <returns></returns>
     public static bool PingIp(string ip)
     {
         System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
         System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
         options.DontFragment = true;
         string data = "Test Data!";
         byte[] buffer = Encoding.ASCII.GetBytes(data);
         int timeout = 2000; // Timeout
         System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
         if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
         {
           //  AddToConvo(ip + reply.Status);
             return true;
         }
         else
         {
            // AddToConvo(ip + reply.Status);
             return false;
         }
     }

👀调用方法

cs 复制代码
  List<string> list = new List<string>();
  list.Add("192.168.1.1");
  list.Add("192.168.3.1");
  list.Add("192.168.4.1");

  foreach (string s in list)
  {
     Console.WriteLine(s+" "+ ccPing.PingIp(s));
        //if(!xxx) 
  }
  
  Thread.Sleep(10000);

隔10秒自动调用1次

📫检查URL

cs 复制代码
        public async Task<bool> IsServerRespondingAsync(string url, TimeSpan timeout)
        {
            try
            {
                using (var cancellationTokenSource = new System.Threading.CancellationTokenSource())
                {
                    cancellationTokenSource.CancelAfter(timeout);
                    var response = await _httpClient.GetAsync(url, cancellationTokenSource.Token);
                    return response.IsSuccessStatusCode;
                }
            }
            catch (TaskCanceledException)
            {
                // 请求超时
                return false;
            }
            catch (Exception)
            {
                // 发生其他错误
                return false;
            }
        }

异步调用

cs 复制代码
 await checker.IsServerRespondingAsync(url, TimeSpan.FromSeconds(2));

如果False可以调用报警代码

END

相关推荐
国思RDIF框架2 天前
RDIFramework.NET CS 敏捷开发框架 V6.3 版本重磅发布!.NET8+Framework双引擎,性能升级全维度进化
后端·.net
用户298698530143 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
赵榕4 天前
ClaimsPrincipal序列化为Json的正确姿势
.net
追逐时光者4 天前
一款使用 C# 编写专为 Windows 11 打造的文件资源管理器增强工具!
后端·.net
用户298698530147 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
牧马人win7 天前
SmartDapper.Repository
.net
mudtools8 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net