.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

相关推荐
iReachers19 小时前
.NET项目集成混淆加密:自动化保护DLL和EXE
.net·代码保护·自动构建·msbuild·c#混淆
完美火龙篇 四月的友1 天前
通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET Core?
.net·.netcore
柠檬香的1 天前
CsGrafeq: 比 Desmos 更“能折腾”的几何函数画板(.NET + Avalonia)
.net
geovindu2 天前
CSharp: Iterative Algorithms
开发语言·后端·算法·c#·.net·迭代算法
geovindu4 天前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
驰骋工作流4 天前
请假流程:六款.NET工作流引擎实现方式对比
.net·ccflow·工作流引擎二开·.net工作流引擎对比
WarPigs4 天前
.NET项目app.Config笔记
c#·.net
海盗12345 天前
微软技术周报——2026-07-22
microsoft·c#·.net
海盗12345 天前
微软技术日报 ——2026-07-21
microsoft·c#·.net
半亩码田5 天前
【.NET新特性·第8篇】.NET 9 AI 构建基块:Microsoft.Extensions.AI
人工智能·microsoft·.net