Monday, January 12, 2009

Ping with .NET

.NET makes pinging a network host to check for availability a piece of cake.

Step 1: To start off with, import the namespaces System.Net.NetworkInformation and System.Net

using System.Net.NetworkInformation;
using System.Net;

Step 2: Instantiate the Ping class

Ping p = new Ping();

Step 3: Call the Send method of the Ping object with the hostname as the parameter. Store the return value as a PingReply object.

PingReply pr = p.Send(@"");

Step 4: From the PingReply object, obtain the ping status from the Status property, the time from sending the ping request to getting the ping reply in milliseconds from the RoundtripTime property, and the IP address of the host from the Address property.

IPStatus status = pr.Status; //IPStatus.Success
IPAddress ipAddr = pr.Address;
long pingTime = pr.RoundtripTime;

The IPStatus enumeration has many different values to describe the problem, if any does occur. For a simple check, you can simply compare the value with IPStatus.Success.

No comments: