简体   繁体   中英

Weird C# Ping Exception

I'm experiencing a very annoying problem in my C# application. For some reason, this code is causing a System.Net.Sockets.SocketException with result: "No such host is known." 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. 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.

Ping does not use the HTTP protocol, it uses ICMP . Changing the code to the following will fix your issue

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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