Saturday, February 18, 2012

How to Ping Machine using C#?



Ping is used to check whether remote machine is reachable or not. We usually use ping.exe to ping machine using command prompt but what when we need to ping remote machine through code. Microsoft Dotnet provides Ping class to ping machine using code. Ping class is available in System.Net.NetworkInformation class. If you can successfully ping remote machine it means you can reach that machine through network.

Ping class provides Send method to request message to remote computer and waits for reply. Ping class also provides SendAsync method to ping remote machine asynchronously. Send method returns PingReply object and we can check status property of pingreply object whether machine reachable or not. Some networks are not allowing ping outside from their network in such case PingException throws.

Following code demonstrate how we can ping remote machine using Ping Class.

string hostname = "www.google.com";
int timeout = 100;
Ping ping = new Ping();
           
try
{
    PingReply reply = ping.Send(hostname, timeout);
    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine("Address: {0}" , reply.Address);
        Console.WriteLine("Round trip time: {0}", reply.RoundtripTime);
        Console.WriteLine("Status: {0}", reply.Status);
    }
}
catch (PingException ex)
{
    Console.WriteLine(ex);
}

Output –
Address: 74.125.236.82
Round trip time: 33
Status: Success


See Also –


1 comment: