Ping多个IP地址并显示绿色完成

本文关键字:显示 多个 IP 地址 Ping | 更新日期: 2023-09-27 18:21:22

我正在尝试ping多个IP地址,如果这些多个IP IP地址ping成功,我希望它将标签颜色更改为绿色。如果它正在ping的2个ip地址中有1个失败,那么我想将标签显示为红色。我该怎么做?

这是我尝试过的,但我得到了错误预期捕获或最终。。。。

    Ping Sender = new Ping();
    // A buffer of 32 bytes of data to be transmitted.
    String Data = "[012345678901234567890123456789]";
    const int Timeout = 120;
    bool Started = false;
    String Hostname1 = "www.google.com";
    String Hostname2 = "www.432446236236.com";
    private void Ping()
    {
        PingReply Reply;
        byte[] Buffer = Encoding.ASCII.GetBytes(Data);
        try { Reply = Sender.Send(Hostname1, Timeout, Buffer); }
        try { Reply = Sender.Send(Hostname2, Timeout, Buffer);}
        catch (Exception ex)
        {
            label1.ForeColor = System.Drawing.Color.Red;
            return;
        }
        if (Reply.Status == IPStatus.Success)
        {
            label1.ForeColor = System.Drawing.Color.Green;
            return;
        }
        label1.ForeColor = System.Drawing.Color.Red;
    }

谢谢。

Ping多个IP地址并显示绿色完成

首先,要回答有关错误的问题:出现错误的原因是在第一个try{}之后没有catch{}块。

我会做几件事:

  1. 私有变量名使用驼色大小写
  2. 将主机放入列表中,以备以后添加或删除一些主机
  3. 使用变量跟踪您的成功
  4. 快速失败:一旦一个失败就停止ping(无需在ping其他任何东西上浪费时间)

代码:

public static void PingTest()
{
    const int timeout = 120;
    const string data = "[012345678901234567890123456789]";
    var buffer = Encoding.ASCII.GetBytes(data);
    PingReply reply;
    var success = true;    // Start out optimistic!
    var sender = new Ping();
    // Add as many hosts as you want to ping to this list
    var hosts = new List<string> {"www.google.com", "www.432446236236.com"};
    // Ping each host and set the success to false if any fail or there's an exception
    foreach (var host in hosts)
    {
        try
        {
            reply = sender.Send(host, timeout, buffer);
            if (reply == null || reply.Status != IPStatus.Success)
            {
                // We failed on this attempt - no need to try any others
                success = false;
                break;
            }
        }
        catch
        {
            success = false;
        }
    }
    if (success)
    {
        label1.ForeColor = System.Drawing.Color.Green;
    }
    else
    {
        label1.ForeColor = System.Drawing.Color.Red;
    }
}