欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现Ping的方法小结

程序员文章站 2023-11-12 15:38:10
本文实例总结了c#实现ping的方法。分享给大家供大家参考。具体如下: 方法一: class program { public string cmdpin...

本文实例总结了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#程序设计有所帮助。