.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

相关推荐
余衫马11 小时前
开发指南:使用 MQTTNet 库构建 .Net 物联网 MQTT 应用程序
物联网·mqtt·.net
William Wang~20 小时前
.net 类库生成的DLL源码混淆加密
.net
一个帅气昵称啊1 天前
Docker命令大全:从基础到高级实战指南
docker·容器·eureka·架构·.net
Eiceblue1 天前
使用 C# 设置 Excel 单元格格式
开发语言·后端·c#·.net·excel
喵叔哟1 天前
58.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--新增功能--图形验证码
微服务·架构·.net
Tiger_shl1 天前
【.Net技术栈梳理】08-控制反转(IoC)与依赖注入(DI)
开发语言·.net·.netcore
Zhen (Evan) Wang1 天前
.NET 6 文件下载
java·前端·.net
周杰伦fans1 天前
.NET 轻量级处理 Excel 文件库 - MiniExce
windows·.net·excel
Tiger_shl1 天前
【.Net技术栈梳理】10-.NET Core 程序的执行
开发语言·.net·.netcore
一个帅气昵称啊2 天前
C# .NET EFCore 性能优化
性能优化·c#·.net