C#實(shí)現(xiàn)Ping的方法小結(jié)
更新時(shí)間:2015年08月12日 12:33:56 作者:dyx2010
這篇文章主要介紹了C#實(shí)現(xiàn)Ping的方法,以兩個(gè)實(shí)例形式形式較為詳細(xì)的分析了C#實(shí)現(xiàn)ping功能的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例總結(jié)了C#實(shí)現(xiàn)Ping的方法。分享給大家供大家參考。具體如下:
方法一:
class Program
{
public string cmdPing(string strIP)
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.UseShellExecute = false;
//要重定向 IO 流,Process 對(duì)象必須將 UseShellExecute 屬性設(shè)置為 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 = "無(wú)法到達(dá)主機(jī)";
else if (strRst.IndexOf("UnKonw host") != -1)
pingstr = "無(wú)法解析主機(jī)";
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();
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
winfrom 在業(yè)務(wù)層實(shí)現(xiàn)事務(wù)控制的小例子
winfrom 在業(yè)務(wù)層實(shí)現(xiàn)事務(wù)控制的小例子,需要的朋友可以參考一下2013-03-03
C# 實(shí)現(xiàn)WebSocket服務(wù)端教程
這篇文章主要介紹了C# 實(shí)現(xiàn)WebSocket服務(wù)端教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
用C#獲取硬盤序列號(hào),CPU序列號(hào),網(wǎng)卡MAC地址的源碼
用C#獲取硬盤序列號(hào),CPU序列號(hào),網(wǎng)卡MAC地址的源碼...2007-03-03
C#動(dòng)態(tài)執(zhí)行批處理命令的方法
這篇文章主要介紹了C#動(dòng)態(tài)執(zhí)行批處理命令的方法,可實(shí)現(xiàn)動(dòng)態(tài)執(zhí)行一系列控制臺(tái)命令,并允許實(shí)時(shí)顯示出來(lái)執(zhí)行結(jié)果,需要的朋友可以參考下2014-11-11
C#從foreach語(yǔ)句中枚舉元素看數(shù)組詳解
這篇文章主要給大家介紹了關(guān)于C#從foreach語(yǔ)句中枚舉元素看數(shù)組的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-05-05

