在我們開發項目時經常會遇到要ping主機的問題,現在我封裝了一個ping主機的方法,
代碼如下:
/// <summary>
/// Ping指定的主機,看能否ping通
/// </summary>
/// <param name="Address">(主機地址www.2cto.com)</param>
/// <param name="TimeOut">(超時時間,默認:1s)</param>
/// <returns>True if a response is received, false otherwise</returns>
public static bool PingHost(string Address, int TimeOut = 1000)
{
using (System.Net.NetworkInformation.Ping PingSender = new System.Net.NetworkInformation.Ping())
{
PingOptions Options = new PingOptions();
Options.DontFragment = true;
string Data = "test";
byte[] DataBuffer = Encoding.ASCII.GetBytes(Data);
PingReply Reply = PingSender.Send(Address, TimeOut, DataBuffer, Options);
if (Reply.Status == IPStatus.Success)
return true;
return false;
}
}
摘自 weizhiai12的專欄