.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

相关推荐
Jeff-Tsai1 天前
Day 22:XML、JSON 与 MessagePack 的分工
.net·架构设计·erp·definition-driven
风云2 天前
从 NLite 到 Vane.Container 1.0:压箱十六年的自研 DI 容器开源
.net·di·mini 容器·nlite
Jeff-Tsai2 天前
Day 21:业务逻辑定制与 Plugin 的四个时点
.net·架构设计·erp·definition-driven
IT规划师2 天前
Redis 核心机制 | 键生命周期与 TTL 管理
redis·.net
Jeff-Tsai3 天前
Day 20:多语言定制与资源结构
.net·架构设计·erp·definition-driven
Jeff-Tsai4 天前
Day 19:定制层的范围与叠加粒度
.net·架构设计·erp·definition-driven
Jeff-Tsai5 天前
Day 18:错误契约与用户可见消息
.net·架构设计·erp·definition-driven
IT规划师5 天前
HybridCache-缓存架构决策框架落地
架构·.net
Jeff-Tsai6 天前
Day 17:Connector 与调用端的职责收敛
.net·架构设计·erp·definition-driven