Ping a host : Ping « Network « C# / C Sharp






Ping a host

        

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

public static class NetUtility
{
    public static bool Ping(string host, int port)
    {
        return Ping(host, port, TimeSpan.MaxValue);
    }
    public static bool Ping(string host, int port, out TimeSpan elapsed)
    {
        return Ping(host, port, TimeSpan.MaxValue, out elapsed);
    }
    public static bool Ping(string host, int port, TimeSpan timeout)
    {
        TimeSpan elapsed;
        return Ping(host, port, timeout, out elapsed);
    }
    public static bool Ping(string host, int port, TimeSpan timeout, out TimeSpan elapsed)
    {
        using (TcpClient tcp = new TcpClient())
        {
            DateTime start = DateTime.Now;
            IAsyncResult result = tcp.BeginConnect(host, port, null, null);
            WaitHandle wait = result.AsyncWaitHandle;
            bool ok = true;

            try
            {
                if (!result.AsyncWaitHandle.WaitOne(timeout, false))
                {
                    tcp.Close();
                    ok = false;
                }

                tcp.EndConnect(result);
            }
            catch
            {
                ok = false;
            }
            finally
            {
                wait.Close();
            }

            DateTime stop = DateTime.Now;
            elapsed = stop.Subtract(start);
            return ok;
        }
    }
}

   
    
    
    
    
    
    
    
  








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.Uses the System.Net.NetworkInformation.Ping class to send an ICMP ping to a specified host asynchronously.
8.Is Internet Connection Available