C# 检查可访问的多个主机

C# 检查可访问的多个主机,c#,ping,C#,Ping,我想使用Ping检查多个主机的可访问性。这是我的密码: void Check_Client(){ string[] hosts=new string[]{ "192.168.2.1", "192.168.2.2", .... ,"192.168.2.100"}; foreach (strings ip in hosts){ AutoResetEvent waiter = new AutoResetEvent(false); Ping pingSen

我想使用Ping检查多个主机的可访问性。这是我的密码:

void Check_Client(){
    string[] hosts=new string[]{ "192.168.2.1", "192.168.2.2", .... ,"192.168.2.100"};
    foreach (strings ip in hosts){
        AutoResetEvent waiter = new AutoResetEvent(false);
        Ping pingSender = new Ping();
        pingSender.PingCompleted += new PingCompletedEventHandler(Ping_Callback);
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //32bytes
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 5000; //12 seconds
        PingOptions options = new PingOptions(2, true);
        pingSender.SendAsync(ip, timeout, buffer, options, waiter);
    }


void Ping_Callback(object sender, PingCompletedEventArgs e){
    if (e.Reply.Status == IPStatus.Success)
    {
        System.Console.Out.WriteLine(e.Reply.Address.ToString() + " accessible");
        ((AutoResetEvent)e.UserState).Set();

    }
    else if(e.Reply.Status == IPStatus.TtlExpired || e.Reply.Status==IPStatus.TimedOut){ 
         System.Console.Out.WriteLine(e.Reply.Address.ToString() + " not accessible");
    }
}
我想打印结果,如下所示:

192.168.2.1  accessible
192.168.2.1  not accessible
192.168.2.2  accessible
....
问题是:

  • 在函数Ping_回调中,如何获取目标IP?e、 答复。地址可以是源IP和目标IP之间的IP地址。它不像192.168.2.2那样是我想要的目标IP。或者我们如何将这个IP地址作为参数传递给回调函数
  • 检测主机是否无法访问的正确方法是什么
根据docs PingReply。Address包含您想要的目的地地址。也许我不明白你的问题?关于检查主机是否可访问的正确方法-使用ping是正确的方法之一:)PingReplay.Address包含路由器和网关的IP地址(如果中间有)。似乎有多个回调用于1 ping。