C#实现Ping的方法小结

时间:2021-05-20

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章