在检查网络上的服务器时在 C# 中处理 Win32Exception

Win32Exception handling in C# while checking for servers down on a network

我的要求是在数据库中的 table 中使用其他可用服务器名称更新停机服务器主机。此记录将使用安装在网络上所有服务器上的 windows 服务来 运行 计划任务。需要帮助来获取在网络上出现故障的服务器主机名 我尝试使用 ping、tcpclient 和 WMI,每次当我的网络上的服务器出现故障时都会出现以下错误:

Message: GetDataBaseHandleWithAccess - INNER Exception:System.ComponentModel.Win32Exception (0x80004005): The RPC server is unavailable

Message: GetDataBaseHandleWithAccessServer Health CheckupSystem.InvalidOperationException: Cannot open Service Control Manager on computer 'VW144444'. This operation might require other privileges. ---> System.ComponentModel.Win32Exception: The RPC server is unavailable --- End of inner exception stack trace ---

以下是我参考并尝试过的 link detect-if-machine-is-online-or-offline-using-wmi-and-c-sharp

csharp-check-if-machine-is-online-or-offline: using Ping Service

how-to-check-a-server-is-alive : using TcpClient

我认为你可以使用异常本身来处理 logic.If 异常包含 RPC 服务器不可用,你可以将其视为服务器未启动。更好的方法是使用 ping,但可以禁用 ping(它使用 ICMP 回显,您的网络管理员可以禁用 ICMP 协议)。因此,如果它是内部域服务器,它很可能会被启用。因此,您可以结合使用 Ping、TcpClient 和 WMI 这三种技术。

我的首选是使用 Ping

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

namespace PingTest
{
public class PingExample
{
    // args[0] can be an IPaddress or host name.
    public static void Main (string[] args)
    {
        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 (args[0], timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {

        }
    }
  }
}

并且如果您正在检查某些特定服务是否已启动,例如 Web 服务,则使用 TcpClient 连接到此服务正在侦听的端口与您链接的相同 SO 问题 How to check a server is alive?