C# Tips

C# Tip Article

How to ping in C#

Ping is typically used to check a computer's availablity. Ping uses ICMP echo request message. If ping is successful, it means that the destination machine is reachable on the network. But the opposite is not always true. That is, even if ping is not successful, the destination machine can be actually alive. This is because something in the middle such as firewall or proxy server can interrupt ping request.

Having said the brief story of ping, now let's look at how to write ping functionality in C#. Actually it is very simple since .NET already provides the Ping class. Here is how-to.

using System;
// for Ping class
using System.Net.NetworkInformation;

namespace PingTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Ping ping = new Ping();	
            // Synchronous call example		
            PingReply reply = ping.Send("csharp.tips");

            Console.WriteLine("Ping IP Address: {0}",reply.Address);
            Console.WriteLine("Ping Status: {0}", reply.Status);
            Console.WriteLine("Ping RoundtripTime: {0}", reply.RoundtripTime);
        }
    }
}

Ping class resides in System.Net.NetworkInformation namespace. We can use .Send() method for synchronous call and .SendAsync() method for asynchronous call.