C# : Check If Machine is Online or Offline

In C#, We can test if a remote computer is online or offline using Ping service. For security reason, the Ping service may be disabled in your network, in that case, you can use WMI service to check if a remote computer is up or down.

Summary:

C# – Check If Machine is Up or Down using Ping Service

You can use the C# class Ping from System.Net.NetworkInformation namespace to find a remote machine is alive or not. This is the fastest way to check a remote machine online status compared with using WMI Service method.

// using System.Net.NetworkInformation;
private static bool IsMachineUp(string hostName)
{
    bool retVal = false;
    try
    {
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions();
        // Use the default Ttl value which is 128,
        // but change the fragmentation behavior.
        options.DontFragment = true;
        // Create a buffer of 32 bytes of data to be transmitted.
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 120;

        PingReply reply = pingSender.Send(hostName, timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            retVal = true;
        }
    }
    catch (Exception ex)
    {
        retVal = false;
        Console.WriteLine(ex.Message);
    }
    return retVal;
}

C# – Check If Machine is Online or Offline using WMI (without Ping Service)

You can use Ping service to get faster results, but for security reason, the Ping service may be disabled in your network, in that case, you can use WMI service in C# to find a remote host is up or down.

// using System.Management;
private static bool IsMachineOnline(string hostName)
{
    bool retVal = false;
    ManagementScope scope = new ManagementScope(string.Format(@"{0}rootcimv2", hostName));
    ManagementClass os = new ManagementClass(scope, new ManagementPath("Win32_OperatingSystem"), null);
    try
    {
        ManagementObjectCollection instances = os.GetInstances();
        retVal = true;
    }
    catch (Exception ex)
    {
        retVal = false;
        Console.WriteLine(ex.Message);
    }
    return retVal;
}

Advertisement

3 thoughts on “C# : Check If Machine is Online or Offline”

Leave a Comment