16.6. Pinging Programmatically
Problem
You want to check a computer's availability on the network.
Solution
Use the System.Net.NetworkInformation.Ping class to determine if a machine is available. In the TestPing method, an instance of the Ping class is created. A ping request is sent using the Send method. The Send method is synchronous and returns a PingReply that can be examined for the result of the ping. You perform the second ping request asynchronously using the SendAsync method, after hooking up to the Ping class for the PingCompleted event. The second parameter of the SendAsync method holds a user token value that will be returned to the pinger_PingCompleted event handler when the ping is complete. This token can be used to identify requests between the initiation and completion code:
public static void TestPing( )
{
System.Net.NetworkInformation.Ping pinger =
new System.Net.NetworkInformation.Ping( );
PingReply reply = pinger.Send("www.oreilly.com");
DisplayPingReplyInfo(reply);
pinger.PingCompleted += pinger_PingCompleted;
pinger.SendAsync("www.oreilly.com", "oreilly ping");
}The DisplayPingReplyInfo method shows some of the more common items you want to know from a ping, such as the RoundtripTime and the Status of the reply. These can be accessed from those properties on the PingReply:
private static void DisplayPingReplyInfo(PingReply reply)
{
Console.WriteLine("Results from pinging " + reply.Address); Console.WriteLine("\tFragmentation allowed?: {0}", !reply.Options.DontFragment); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access