由于并非所有机器都会响应 ping(取决于防火墙设置),因此我建议尽可能跳过第 1 步。
如果您知道要连接以响应 ping 的机器,那么 ping 类就可以很好地工作。它只发送 1 个数据包,因此 ping 不止一次,以防它被丢弃。此外,根据我的经验,如果主机无法访问,ping 类通常会抛出异常而不是返回 PingReply 对象。
这是我建议的实现:
public bool
Ping (string host, int attempts, int timeout)
{
System.Net.NetworkInformation.Ping ping =
new System.Net.NetworkInformation.Ping ();
System.Net.NetworkInformation.PingReply pingReply;
for (int i = 0; i < attempts; i++)
{
try
{
pingReply = ping.Send (host, timeout);
// If there is a successful ping then return true.
if (pingReply != null &&
pingReply.Status == System.Net.NetworkInformation.IPStatus.Success)
return true;
}
catch
{
// Do nothing and let it try again until the attempts are exausted.
// Exceptions are thrown for normal ping failurs like address lookup
// failed. For this reason we are supressing errors.
}
}
// Return false if we can't successfully ping the server after several attempts.
return false;
}