C#实现Ping的方法小结
内容摘要
本文实例总结了C#实现Ping的方法。分享给大家供大家参考。具体如下:
方法一:
class Program
{
public string cmdPing(string strIP)
{
Process myProcess = new Proce
方法一:
class Program
{
public string cmdPing(string strIP)
{
Process myProcess = new Proce
文章正文
本文实例总结了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#程序设计有所帮助。
代码注释