System.Net.NetworkInformation – Ping Diagnostic Test Application Development 方法
Main.cs |
using System; using System.Net.NetworkInformation; namespace PingApps { class Program { static void Main(string[] args) { string hostname = "192.168.5.100"; while(true) { if (getReachable(hostname)) { Console.WriteLine(hostname + " Reachable"); } else { Console.WriteLine(hostname + " Unreachable"); } Console.ReadLine(); } } private static bool getReachable(string hostname) { Ping ping = new Ping(); PingReply reply; int i = 0; //int a = 0; bool change = false; while(true) { try { /* if (i == 2 && a == 0) { hostname = "192.168.5.101"; a++; } else if (a == 1 && i == 2) { hostname = "192.168.5.100"; } */ reply = ping.Send(hostname); Console.WriteLine(i + " " + reply.Status + " "); if (reply.Status == IPStatus.Success) { if (i >= 4) { return true; } else if (!change && i != 0) { i = 0; } else { i++; } change = true; } else { if (i >= 4) { return false; } else if (change && i != 0) { i = 0; } else { i++; } change = false; } } catch (Exception ex) { Console.WriteLine(i + " " + ex.Message); if (i >= 4) { return false; } else if (change && i != 0) { i = 0; } else { i++; } change = false; } } } } } |