C# helper function to ping a network host.
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Collections.Generic;
namespace MyNamespace
{
public static class PingHelper
{
public static PingResult PingHost(string host, int timeout = 1000,
int pingCount = 4, int waitTime = 100)
{
PingResult pingResult = new PingResult();
IPAddress address = GetIpFromHost(host);
byte[] buffer = new byte[32];
PingOptions pingOptions = new PingOptions(128, true);
using (Ping ping = new Ping())
{
for (int i = 0; i < pingCount; i++)
{
try
{
PingReply pingReply = ping.Send(address, timeout, buffer, pingOptions);
if (pingReply != null)
{
pingResult.PingReplyList.Add(pingReply);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
if (waitTime > 0 && i + 1 < pingCount)
{
Thread.Sleep(waitTime);
}
}
}
return pingResult;
}
private static IPAddress GetIpFromHost(string host)
{
IPAddress address;
if (!IPAddress.TryParse(host, out address))
{
try
{
address = Dns.GetHostEntry(host).AddressList[0];
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
return address;
}
}
public class PingResult
{
public List<PingReply> PingReplyList { get; private set; }
public int Min
{
get
{
return (int)PingReplyList.Where(x => x.Status == IPStatus.Success).Min(x => x.RoundtripTime);
}
}
public int Max
{
get
{
return (int)PingReplyList.Where(x => x.Status == IPStatus.Success).Max(x => x.RoundtripTime);
}
}
public int Average
{
get
{
return (int)PingReplyList.Where(x => x.Status == IPStatus.Success).Average(x => x.RoundtripTime);
}
}
public PingResult()
{
PingReplyList = new List<PingReply>();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (PingReply pingReply in PingReplyList)
{
if (pingReply != null)
{
switch (pingReply.Status)
{
case IPStatus.Success:
sb.AppendLine(string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl));
break;
case IPStatus.TimedOut:
sb.AppendLine("Request timed out.");
break;
default:
sb.AppendLine(string.Format("Ping failed: {0}", pingReply.Status.ToString()));
break;
}
}
}
if (PingReplyList.Any(x => x.Status == IPStatus.Success))
{
sb.AppendLine(string.Format("Minimum = {0}ms, Maximum = {1}ms, Average = {2}ms", Min, Max, Average));
}
return sb.ToString().Trim();
}
}
}