我正在尝试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;
}
谢谢。
答案 0 :(得分:0)
首先,要回答有关错误的问题:您收到错误的原因是您在第一次catch{}
之后没有try{}
阻止。
我会做几件事:
代码:
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;
}
}