using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Globalization;
namespace PingClient
{
public class PingCommon
{
/// <summary>
/// Ping的实例
/// </summary>
private Ping pingClient = null;
/// <summary>
/// 结果字符串
/// </summary>
private StringBuilder strMsg = null;
public PingCommon()
{
pingClient = new Ping();
strMsg = new StringBuilder();
pingClient.PingCompleted += new PingCompletedEventHandler(pingClient_PingCompleted);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pingClient_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Error == null)
{
if (e.Cancelled)
{
strMsg.Append(" Ping cancelled. \r\n");
}
else
{
if (e.Reply.Status == IPStatus.Success)
{
strMsg.AppendFormat(" {0} {1} ms\r\n", e.Reply.Address.ToString(), e.Reply.RoundtripTime.ToString(NumberFormatInfo.CurrentInfo));
}
else
{
strMsg.AppendFormat(" {0}\r\n", GetStatusString(e.Reply.Status));
}
}
}
else
{
strMsg.Append(" Ping error.\r\n");
}
}
/// <summary>
/// Ping的状态
/// </summary>
/// <param name="status">Ping的原始状态</param>
/// <returns>返回状态结果</returns>
private string GetStatusString(IPStatus status)
{
string strResult = string.Empty;
switch (status)
{
case IPStatus.Success:
strResult = "Success.";
break;
case IPStatus.DestinationHostUnreachable:
strResult = "Destination host unreachable.";
break;
case IPStatus.DestinationNetworkUnreachable:
strResult = "Destination network unreachable.";
break;
case IPStatus.DestinationPortUnreachable:
strResult = "Destination port unreachable.";
break;
case IPStatus.DestinationProtocolUnreachable:
strResult = "Destination protocol unreachable.";
break;
case IPStatus.PacketTooBig:
strResult = "Packet too big.";
break;
case IPStatus.TtlExpired:
strResult = "TTL expired.";
break;
case IPStatus.ParameterProblem:
strResult = "Parameter problem.";
break;
case IPStatus.SourceQuench:
strResult = "Source quench.";
break;
case IPStatus.TimedOut:
strResult = "Timed out.";
break;
default:
strResult = "Ping failed.";
break;
}
return strResult;
}
/// <summary>
/// 发送Ping
/// </summary>
/// <param name="address"></param>
public void SendPing(string address)
{
if (address.Length > 0)
{
strMsg.AppendFormat("Pinging {0} . . .\r\n", address);
pingClient.SendAsync(address, null);
}
else
{
strMsg.Append("Please enter an IP address or host name.");
}
}
/// <summary>
/// 取消Ping
/// </summary>
public void CancelPing()
{
pingClient.SendAsyncCancel();
}
/// <summary>
/// 获取Ping结果
/// </summary>
/// <returns></returns>
public string GetPingResult()
{
return strMsg.ToString();
}
}
}