The Ping class is new to .NET 2.0 and it let’s you ping remote addresses much the same way as the ping.exe command line tool does. It’s a great way to check the availability of different kinds of remote servers over the network in a very low cost and fast way. The most important result a ping can give you is the ping time. The ping time gives you an indication on the network speed between you and the server.
I’ve written a very small and easy to use method that returns the ping time of a given URL.
using System.Net.NetworkInformation;
/// <summary>
/// Pings
the specified URL within the timeout period.
/// </summary>
/// <param
name="url">The
URL to ping.</param>
/// <param
name="timeout">Number
of milliseconds.</param>
/// <returns>Returns
the ping time in milliseconds.</returns>
private static long PingTime(string url, int timeout)
{
try
{
using (Ping ping
= new
{
PingReply reply
= ping.Send(url, timeout);
return reply.RoundtripTime;
}
}
catch (System.Net.Sockets.SocketException)
{
return -1;
}
}
You can use the method from whenever you want like the following an ASP.NET webpage.
Response.Write(PingTime("http://www.google.com", 2000));
Comments
What did you think?