C#实现Ping的方法小结
作者:dyx2010
这篇文章主要介绍了C#实现Ping的方法,以两个实例形式形式较为详细的分析了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#程序设计有所帮助。