In this short article I want to show a useful code snippet that allows you to ping a remote computer, much like the command line tool ping.exe. This particular code snippet was taken from a Smoke Test from the Post Deployment Smoke Testing tool that I am the open source moderator for.

Usage of the PingHost method is very straight forward. You just call it and pass in a host name. In the example below that is “www.google.co.uk”, but it could be a server name or ip address.

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

namespace PingTester
{
    class Program
    {
        static void Main(string[] args)
        {
            string reply = PingHost("www.google.co.uk");
            Console.WriteLine(reply);
        }

        private static string PingHost(string host)
        {
            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentNullException("host");
            }

            var returnMessage = string.Empty;

            try
            {
                var address = GetIpFromHost(host);
                var pingOptions = new PingOptions(128, true);
                var ping = new Ping();
                var buffer = new byte[32];

                for (var i = 0; i < 4; i++)
                {
                    try
                    {
                        var pingReply = ping.Send(address, 5000, buffer, pingOptions);

                        if (pingReply != null)
                        {
                            switch (pingReply.Status)
                            {
                                case IPStatus.Success:
                                    returnMessage = string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}",
                                        pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime,
                                        pingReply.Options.Ttl);
                                    break;
                                case IPStatus.TimedOut:
                                    returnMessage = "Connection has timed out...";
                                    break;
                                default:
                                    returnMessage = string.Format("Ping failed: {0}", pingReply.Status);
                                    break;
                            }
                        }
                        else
                            returnMessage = "Connection failed for an unknown reason...";
                    }
                    catch (PingException ex)
                    {
                        returnMessage = string.Format("Connection Error: {0}", ex.Message);
                    }
                    catch (SocketException ex)
                    {
                        returnMessage = string.Format("Connection Error: {0}", ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Connection failed for an unknown reason...");
            }

            return returnMessage;
        }

        private static IPAddress GetIpFromHost(string host)
        {
            var address = Dns.GetHostEntry(host).AddressList[0];
            return address;
        }
    }
}

First of all a call is made to GetIpFromHost, which in turn call the .NET Dns.GetHostEntry method to resolve to an IP address. Then a call is made to Ping.Send(). At this point you will either get a success status or a timeout.  One thing to note though is that some enterprises have Ping disabled using group policy. If this is the case then you will get a “Connection has timed out error.”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s