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

时间:2014-09-10 23:52:53

标签: c#

我正在尝试ping多个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;
    }

谢谢。

1 个答案:

答案 0 :(得分:0)

首先,要回答有关错误的问题:您收到错误的原因是您在第一次catch{}之后没有try{}阻止。

我会做几件事:

  1. 将camel case用于私有变量名称
  2. 将主机放入列表中,以备日后添加或删除时使用
  3. 使用变量跟踪您的成功
  4. 快速失败:一旦失败就停止ping(不需要浪费时间ping任何其他人)
  5. 代码:

    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;
        }
    }