Ping 是 dos cmd 網絡實用程式,將訊號透過網絡傳送至另一部電腦,然後另一部電腦再將其訊號傳回。 這種訊號以毫秒(ms) 為量度單位,讓你知悉將數據封包由電腦傳輸至互聯網伺服器後再傳回所需的時間。 此量度值是指電腦與其伺服器之間的延遲。
public bool Ping(string nameOrAddress, string timeout)
{
bool pingable = false;
int pingcnt = 0;
try
{
string pingrst;
Process p = new Process();
p.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ping -n 6 " + nameOrAddress + " -w " + timeout);
p.StandardInput.WriteLine("exit");
CommonData.pFindStr.Source = p.StandardOutput.ReadToEnd();
if (CommonData.pFindStr.Source.IndexOf("TTL=") != -1)
{
pingcnt = SubstringCount(CommonData.pFindStr.Source, "TTL=");
if (pingcnt > 2)
{
CommonData.WriteMessage(CommonData.richtextbox, DateTime.Now.ToString() + CommonData.pFindStr.Source, "", Color.Blue, Color.Green);
pingrst = "連接";
CommonData.WriteMessage(CommonData.richtextbox, pingrst, pingcnt.ToString(), Color.Blue, Color.Green);
pingable = true;
}
}
else if (CommonData.pFindStr.Source.IndexOf("Destination host unreachable.") != -1 || CommonData.pFindStr.Source.IndexOf("一般失敗") != -1)
{
//一般失敗
this.GridData.WriteMessage(this.GridData._TPars.richtextbox, DateTime.Now.ToString() + CommonData.pFindStr.Source, "", Color.Blue, Color.Green);
pingrst = "無法到達目的主機";
this.GridData.WriteMessage(this.GridData._TPars.richtextbox, pingrst, "", Color.Blue, Color.Green);
}
else if (CommonData.pFindStr.Source.IndexOf("Request timed out.") != -1 || CommonData.pFindStr.Source.IndexOf("要求等候逾時") != -1)
{
//要求等候逾時
this.GridData.WriteMessage(this.GridData._TPars.richtextbox, DateTime.Now.ToString() + CommonData.pFindStr.Source, "", Color.Blue, Color.Green);
pingrst = "超時";
this.GridData.WriteMessage(this.GridData._TPars.richtextbox, pingrst, "", Color.Blue, Color.Green);
}
else if (CommonData.pFindStr.Source.IndexOf("Unknown host") != -1)
{
this.GridData.WriteMessage(this.GridData._TPars.richtextbox, DateTime.Now.ToString() + CommonData.pFindStr.Source, "", Color.Blue, Color.Green);
pingrst = "無法解析主機";
this.GridData.WriteMessage(this.GridData._TPars.richtextbox, pingrst, "", Color.Blue, Color.Green);
}
p.Close();
}
catch (Exception e)
{
CommonData.WriteMessage(CommonData.richtextbox, e.Message, "", Color.Red, Color.Green);
}
return pingable;
}