我的代码ping成功,但现在可以工作了。
public static bool IsHostnameAlive(string address)
{
bool Alive = false;
try
{
Ping ping = new Ping();
PingReply reply = ping.Send(address);
Alive = (reply.Status == IPStatus.Success);
MessageBox.Show(address + " is online.");
}
catch
{
Alive = false;
MessageBox.Show(address + " is offline or does not allow ICMP traffic.");
}
return Alive;
}假设地址是http://www.example.com/
我会ping它,它会说它是离线的。
如果我将地址更改为example.com
它会说它是在线的。
但是,如果我要ping一个不存在的地址,例如: idfnwjfneriugelhfnaiorfge.com
它会说这也是在线的,而不是在线的。
有人知道它为什么这样做吗?
发布于 2013-11-25 01:56:37
即使ping失败,你也要说it it online:
MessageBox.Show(address + " is online.");我猜你想把它改成:
if (Alive) {
MessageBox.Show(address + " is online.");
else {
MessageBox.Show(address + " is offline or does not allow ICMP traffic.");
}当您尝试ping无效地址(不是IP或有效DNS名的地址)时,catch会处理该地址。但是如果你尝试ping一个有效的IP或DNS名称(例如192.168.200.237),但是没有响应,你可以将Alive设置为false,但随后你会显示一个消息框,告诉你192.168.200.237在线。。
https://stackoverflow.com/questions/20177720
复制相似问题