Mega Code Archive

 
Categories / C# / Network
 

Uses the System Net NetworkInformation Ping class to send an ICMP ping to a specified host asynchronously

using System.Net.NetworkInformation; using System; namespace Gildor.SimpleHostMonitor.Desktop.Utilities {     /// <summary>     /// Uses the <see cref="System.Net.NetworkInformation.Ping"/> class      /// to send an ICMP ping to a specified host asynchronously.     /// </summary>     class Pinger     {         /// <summary>         /// The maximum timeout in milliseconds of the ping operation.         /// </summary>         public static readonly int MaxTimeOut = 4000;         /// <summary>         /// Pings the specified ip.         /// </summary>         /// <param name="ip">The ip.</param>         /// <param name="callback">The callback.</param>         public static void Ping(string ip, PingCompletedEventHandler callback)         {             Ping(ip, callback, ip, 3000);         }         /// <summary>         /// Pings the specified ip.         /// </summary>         /// <param name="ip">The ip.</param>         /// <param name="callback">The callback.</param>         /// <param name="userToken">The user token.</param>         /// <param name="timeout">The timeout (in milliseconds). </param>         public static void Ping(string ip, PingCompletedEventHandler callback, object userToken, int timeout)         {             if (timeout > MaxTimeOut)             {                 throw new ArgumentOutOfRangeException("timeout");             }             //Ping object is disposable. It should be disposed when ping is completed.             Ping ping = new Ping();             ping.PingCompleted += callback;             ping.SendAsync(ip, timeout, userToken);         }     } }