我在C#中使用Ping.SendAsync()函数遇到了问题。 我ping一些IP地址,但其中一些是错误的。我需要从列表中删除错误的地址。但是如何操作呢?因为p_PingCompleted事件参数replay.adress是0.0.0.0? 以下是我的代码:
System.Collections.Generic.List<Game> GameList = new System.Collections.Generic.List<Game>();
System.Timers.Timer timer = new System.Timers.Timer(5000);
public StartServer()
{
this.tcpListener = new TcpListener(IPAddress.Any, 8888);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
Console.WriteLine("Master server running...");
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Game[] games = GameList.ToArray();
foreach (Game curgame in games)
{
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
p.PingCompleted += new System.Net.NetworkInformation.PingCompletedEventHandler(p_PingCompleted);
p.SendAsync(IPAddress.Parse(curgame.IP), new object());
}
SendMessageToAll(output);
Console.WriteLine("Timer.Elapsed with data [" + output + "]");
}
void p_PingCompleted(object sender, System.Net.NetworkInformation.PingCompletedEventArgs e)
{
Console.WriteLine("Ping reply from: " + e.Reply.Address.ToString() + " has " + e.Reply.RoundtripTime.ToString() + " ms.");
if (e.Reply.RoundtripTime == 0 ||
e.Reply.RoundtripTime >= 2500)
{
Console.WriteLine(" Removing this server because ping is 0 or is greater than 2500 ms");
}
}
输出结果为:
Pinging 16.5.4.3... Ping reply from: 0.0.0.0 has 0 ms.
PingReply.Status
大概会像目标不可达一样。 - user7116