Often you may need to ping a server or host from C#. Using this code you can pass either the IP Address or full domain, eg www.google.com, and it will return whether the hosts was resolved, responded, and if so, the round trip in milliseconds.
Please note that if a server or host fails to respond to a ping request it does not necessarily mean it is offline – often ping requests are blocked by firewalls – so use this as an indicator only.
class PING
{
protected static string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
protected static byte[] buffer = Encoding.ASCII.GetBytes(data);
protected static int timeout = 300;
internal static string Response(string Hostname)
{
PingReply reply;
string result = String.Empty;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
try
{
reply = pingSender.Send(Hostname, timeout, buffer, options);
}
catch (System.Net.NetworkInformation.PingException)
{
return ("Failed: Host unknown.");
}
if (reply.Status == IPStatus.Success)
{
result = String.Format("{0}: {1}ms", "Success", reply.RoundtripTime);
}
else
{
result = String.Format("Failed: Host failed to reply.");
}
return (result);
}
}