C#?實現Ping遠程主機功能及代碼演示
1、引用nuget包 Wesky.Net.OpenTools
OpenTools是一個用于提高開發(fā)效率的開源工具庫。該項目為個人開源項目,采用MIT開源協(xié)議,永不更改協(xié)議。開源項目地址:
Gitee:https://gitee.com/dreamer_j/open-tools.git
Github:https://github.com/LittleLittleRobot/OpenTools.git
工具更新說明:
1.0.1 提供AES加密解密功能
1.0.2 提供本地Ping遠程主機功能,包括支持IP地址、域名
本教程將演示1.0.2版本更新功能,以及實現的具體代碼演示。
咱們先看一下正常的Ping的效果:
引用nuget包以后,只需要直接調用:
PingHelper.PingHost方法即可,第一個參數是IP地址或域名,第二個是超時時間,單位毫秒.
具體源碼和實現說明:
/// <summary> /// 對指定主機執(zhí)行 ping 操作并返回結果 /// Ping the specified host and return the result /// </summary> /// <param name="host">需要被 ping 的主機或 IP 地址 The hostname or IP address to ping</param> /// <param name="timeout">ping 超時時間,以毫秒為單位 Timeout duration in milliseconds for ping</param> /// <returns>包含 ping 操作結果的 PingResultInfo 對象 A PingResultInfo object containing the result of the ping operation</returns> public static PingResultInfo PingHost(string host, int timeout) { try { // 解析域名獲取 IP 地址 // Resolve the domain name to get IP address IPAddress[] addresses = Dns.GetHostAddresses(host); if (addresses.Length == 0) { return new PingResultInfo { Host = null, Result = false, Message = "No IP addresses resolved" }; } using (Ping pingSender = new Ping()) { PingOptions options = new PingOptions { // 設置防止數據包被分片 DontFragment = true // Prevent packet fragmentation }; // 數據緩沖區(qū),包含要發(fā)送的字符串數據 // Data buffer containing the string data to send string data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"; byte[] buffer = Encoding.ASCII.GetBytes(data); // 使用第一個解析的 IP 地址進行 ping 操作 // Use the first resolved IP address to perform the ping IPAddress targetIP = addresses[0]; // 發(fā)送 ping 請求并獲取回復 // Send the ping request and obtain the reply PingReply reply = pingSender.Send(targetIP, timeout, buffer, options); // 創(chuàng)建并返回包含 ping 操作結果的 PingResultInfo 對象 // Create and return a PingResultInfo object containing the ping result return new PingResultInfo { Host = targetIP, Result = reply.Status == IPStatus.Success, Message = reply.Status == IPStatus.Success ? $"Success: RoundTrip time={reply.RoundtripTime}ms; TTL={reply.Options.Ttl}; Data size={buffer.Length} bytes" : $"Failed: Status={reply.Status}", RoundTripTime = reply.Status == IPStatus.Success ? reply.RoundtripTime : -1, Ttl = reply.Status == IPStatus.Success ? reply.Options.Ttl : -1, DataSize = buffer.Length }; } } catch (Exception e) { // 捕獲異常并返回錯誤信息 // Catch any exceptions and return error information return new PingResultInfo { Host = null, Result = false, Message = $"錯誤: {e.Message} Error: {e.Message}" }; } }
我們也可以直接PING域名,例如 www.baidu.com
并且可以自動解析出來該域名的IP地址(Host)
如果Ping一個不存在的IP,或者連不上的,例如192.168.0.1
顯示超時,并且Result狀態(tài)為false,代表沒連上。狀態(tài)值為TimeOut,說明超時了。
應用場景:
該功能可以應用于需要不定時驗證某個遠程主機或設備或其他機器是否還在線的情況。并根據狀態(tài)來展示具體主機是在線還是掉線。
到此這篇關于C# 實現Ping遠程主機功能的文章就介紹到這了,更多相關C# Ping遠程主機內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!