.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

相关推荐
随心(cracker)10 小时前
BeaverX Admin:一套真正能跑起来的开源管理后台
vue·.net·管理后台
忧郁的紫菜14 小时前
异步编程 In .NET
.net
Denuin多啦咧梦17 小时前
玩转 .NET 依赖注入:Microsoft.Extensions.DependencyInjection 深度指南
c#·.net·依赖注入
长孙豪翔1 天前
在.net中读写config文件的各种方法
java·数据库·.net
GV191rLvq2 天前
查看w3wp进程占用的内存及.NET内存泄露,死锁分析
.net
界面开发小八哥2 天前
界面控件DevExpress .NET Reports v26.1新版亮点 - 持续增强可访问性
.net·界面控件·devexpress·ui开发·报表控件
wei1986212 天前
.net添加web引用和添加服务引用有什么区别?
java·前端·.net
pW3g3lLuu3 天前
.NET 高级开发 | http 接口对接和客户端开发技巧
网络协议·http·.net
CSharp精选营4 天前
.NET 8 与 .NET 9 支持终止倒计时:开发者需要了解什么
.net·lts·.net8·.net9·码农刚子·升级迁移·sts·支持终止
hez20106 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr