Using ping in c#

Black Star picture Black Star · Aug 3, 2012 · Viewed 204.8k times · Source

When I Ping a remote system with windows it says there is no reply, but when I ping with c# it says success. Windows is correct, the device is not connected. Why is my code able to successfully ping when Windows is not?

Here is my code :

Ping p1 = new Ping();
PingReply PR = p1.Send("192.168.2.18");
// check when the ping is not success
while (!PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}
// check after the ping is n success
while (PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}

Answer

JamieSee picture JamieSee · Aug 4, 2012
using System.Net.NetworkInformation;    

public static bool PingHost(string nameOrAddress)
{
    bool pingable = false;
    Ping pinger = null;

    try
    {
        pinger = new Ping();
        PingReply reply = pinger.Send(nameOrAddress);
        pingable = reply.Status == IPStatus.Success;
    }
    catch (PingException)
    {
        // Discard PingExceptions and return false;
    }
    finally
    {
        if (pinger != null)
        {
            pinger.Dispose();
        }
    }

    return pingable;
}