C#應用ping敕令的兩個例子。本站提示廣大學習愛好者:(C#應用ping敕令的兩個例子)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用ping敕令的兩個例子正文
辦法一:挪用cmd 的ping敕令
private static string CmdPing(string strIp)
{
Process p = new Process(); p.StartInfo.FileName = "cmd.exe";//設定法式名
p.StartInfo.UseShellExecute = false; //封閉Shell的應用
p.StartInfo.RedirectStandardInput = true;//重定向尺度輸出
p.StartInfo.RedirectStandardOutput = true;//重定向尺度輸入
p.StartInfo.RedirectStandardError = true;//重定向毛病輸入
p.StartInfo.CreateNoWindow = true;//設置不顯示窗口
string pingrst; p.Start(); p.StandardInput.WriteLine("ping " + strIp);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
if (strRst.IndexOf("(0% loss)") != -1)
{
pingrst = "銜接";
}
else if (strRst.IndexOf("Destination host unreachable.") != -1)
{
pingrst = "沒法達到目標主機";
}
else if (strRst.IndexOf("Request timed out.") != -1)
{
pingrst = "超時";
}
else if (strRst.IndexOf("Unknown host") != -1)
{
pingrst = "沒法解析主機";
}
else
{
pingrst = strRst;
}
p.Close();
return pingrst;
}
辦法二:應用C#中的ping 類
private void displayReply(PingReply reply) //顯示成果
{
Ping p1 = new Ping(); //只是演示,沒有做毛病處置
PingReply reply = p1.Send("填寫ip地址");
StringBuilder sbuilder ;
if (reply.Status == IPStatus.Success)
{
sbuilder = new StringBuilder();
sbuilder.Append(string.Format("Address: {0} ", reply.Address.ToString ()));
sbuilder.Append(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
sbuilder.Append(string.Format("Time to live: {0} ", reply.Options.Ttl));
sbuilder.Append(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
sbuilder.Append(string.Format("Buffer size: {0} ", reply.Buffer.Length));
response.write(sbuilder.ToString());
}
else if (reply.Status == IPStatus.TimeOut)
{
response.write("超時");
}else{
response.write("掉敗");
}