简体   繁体   English

奇怪的C#Ping异常

[英]Weird C# Ping Exception

I'm experiencing a very annoying problem in my C# application. 我的C#应用​​程序遇到了一个非常烦人的问题。 For some reason, this code is causing a System.Net.Sockets.SocketException with result: "No such host is known." 由于某种原因,此代码导致System.Net.Sockets.SocketException,其结果为:“未知此类主机”。 and 'connected' is always false. “连接”始终为假。

bool connected;

try {
    Ping pinger = new Ping();
    PingReply reply = pinger.Send("http://www.google.com", 15000);
    connected = reply != null && reply.Status == IPStatus.Success;
} catch {
}

The strange thing is that both pinging using the command prompt and http requests all result in success. 奇怪的是,使用命令提示符ping和http请求都可以成功执行。 Does anyone have any idea why this code is failing? 有谁知道为什么此代码失败?

It's failing because it's taking the http:// as part of the host name, rather than the protocol. 之所以失败,是因为它将http://作为主机名而不是协议的一部分。

Ping does not use the HTTP protocol, it uses ICMP . Ping不使用HTTP协议,而是使用ICMP Changing the code to the following will fix your issue 将代码更改为以下代码将解决您的问题

Ping pinger = new Ping();
PingReply reply = pinger.Send("www.google.com", 15000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM