Why?
Sometimes, you need to know whether a Server is down.
Code:
private void btnPing_Click(object sender, RoutedEventArgs e)
{
PingAsync("www.google.com", "I send myself to the callback method");
}
private static void PingAsync(string hostName, object toBeSent)
{
var pinger = new Ping();
pinger.PingCompleted += pinger_PingCompleted;
pinger.SendAsync(hostName, toBeSent);
}
private static void pinger_PingCompleted(object sender, PingCompletedEventArgs e)
{
PingReply reply = e.Reply;
DisplayPingReplyInfo(reply);
if (e.Cancelled)
{
Console.WriteLine("Ping for " + e.UserState.ToString() + " was cancelled");
}
else if (e.Error != null)
{
Console.WriteLine("Exception thrown during ping: {0}", e.Error.ToString());
}
}
private static void DisplayPingReplyInfo(PingReply reply)
{
Console.WriteLine("Results from pinging " + reply.Address);
Console.WriteLine("\tFragmentation allowed?: {0}", !reply.Options.DontFragment);
Console.WriteLine("\tTime to live: {0}", reply.Options.Ttl);
Console.WriteLine("\tRoundtrip took: {0}", reply.RoundtripTime);
Console.WriteLine("\tStatus: {0}", reply.Status.ToString());
}
Unsuccessful Ping:
If a computer is not reached successfully by the ping request, it does not necessarily mean that the computer is unreachable. Many factors can prevent a ping from succeeding such as:
- The machine being offline
- Network topology
- Firewalls
- Packet filters
- Proxy servers
More details:
No comments:
Post a Comment