检查多个主机可访问

时间:2014-11-12 13:04:42

标签: 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 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_Callback中,如何获取目标IP? e.Reply.Address可以是源IP和目标IP之间的IP地址。它不是我想要的目标IP,如192.168.2.2。或者我们如何将此IP地址作为参数传递给回调函数?
  • 检测主机是否无法访问的正确方法是什么?

0 个答案:

没有答案