亲宝软件园·资讯

展开

C#实现Ping的方法 C#实现Ping的方法小结

dyx2010 人气:0
想了解C#实现Ping的方法小结的相关内容吗,dyx2010在本文为您仔细讲解C#实现Ping的方法的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,Ping,下面大家一起来学习吧。

本文实例总结了C#实现Ping的方法。分享给大家供大家参考。具体如下:

方法一:

class Program
{
 public string cmdPing(string strIP)
 {
   Process myProcess = new Process();
   myProcess.StartInfo.FileName = "cmd.exe";
   myProcess.StartInfo.UseShellExecute = false;
   //要重定向 IO 流,Process 对象必须将 UseShellExecute 属性设置为 False。
   myProcess.StartInfo.RedirectStandardOutput = true;
   myProcess.StartInfo.RedirectStandardInput = true;
   myProcess.StartInfo.RedirectStandardError = true;
   string pingstr;
   myProcess.Start();
   myProcess.StandardInput.WriteLine("ping " + strIP);
   myProcess.StandardInput.WriteLine("exit");
   string strRst = myProcess.StandardOutput.ReadToEnd();
   if (strRst.IndexOf("(0% loss)") != -1)
   pingstr = "连接";
   else if (strRst.IndexOf("Destination host unreachable.") != -1)
   pingstr = "无法到达主机";
   else if (strRst.IndexOf("UnKonw host") != -1)
   pingstr = "无法解析主机";
   else
   pingstr = strRst;
   myProcess.Close();
   return pingstr;
 }
 static void Main(string[] args)
 {
  Program myProgram = new Program();
  string returnString = myProgram.cmdPing("127.0.0.1");
  Console.WriteLine(returnString);
  Console.ReadLine();
 }
}

方法二:

static void Main(string[] args)
{
  Ping ping = new Ping();
  PingOptions pingOption = new PingOptions(50, true);
  string data = " you are a such a beautiful girl";
  byte[] buffer = Encoding.ASCII.GetBytes(data);
  PingReply pingReply = ping.Send("192.168.1.100", 20, buffer);
  if (pingReply.Status == IPStatus.Success)
  {
   Console.WriteLine("address:{0}", pingReply.Address.ToString());
   Console.WriteLine("Round Trip time {0}", pingReply.RoundtripTime);
   Console.WriteLine("time to live:{0}", pingReply.Options.Ttl);
   Console.WriteLine("Do not to fragement:{0}", pingReply.Options.DontFragment);
  }
  Console.ReadKey();
}

希望本文所述对大家的C#程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论