最近在项目开发中遇到了设备连接的问题,连接完设备后需要需要判断设备有没有断开,方法一就是使用cmd中的ping命令来看设备是否可以连通
public 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("无法访问目标主机") != -1)
{
pingrst = "无法访问目标主机";
}
else if (strRst.IndexOf("Unknown host") != -1)
{
pingrst = "无法解析主机";
}
else if(strRst.IndexOf("TTL") != -1&&strRst.IndexOf("字节") != -1&& strRst.IndexOf("时间") != -1)
{
pingrst = "success";
}
p.Close();
return pingrst;
}
方法二:
public static string CmdPing(string IPAddress)
{
Ping p1 = new Ping();
PingReply reply = p1.Send(IPAddress); //发送主机名或Ip地址
StringBuilder sbuilder;
if (reply.Status == IPStatus.Success)
{
sbuilder = new StringBuilder();
sbuilder.AppendLine(string.Format("Address: {0} ", reply.Address.ToString()));
sbuilder.AppendLine(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
sbuilder.AppendLine(string.Format("Time to live: {0} ", reply.Options.Ttl));
sbuilder.AppendLine(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
sbuilder.AppendLine(string.Format("Buffer size: {0} ", reply.Buffer.Length));
Console.WriteLine(sbuilder.ToString());
}
else if (reply.Status == IPStatus.TimedOut)
{
Console.WriteLine("超时");
}
else
{
Console.WriteLine("失败");
}
return reply.Status.ToString();
}