Uses the System.Net.NetworkInformation.Ping class to send an ICMP ping to a specified host asynchronously. : Ping « Network « C# / C Sharp






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);
        }
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Success
2.Ping and PingReply
3.Ping Success and Send
4.Advanced Ping ProgramAdvanced Ping Program
5.Simple Ping
6.This method checks if there is a connection at all
7.Ping a host
8.Is Internet Connection Available