C# and .NET basics: how to ping a host
Posted: (EET/GMT+2)
From time to time, you need quick and simple solutions without much hassle. Just this week, I needed to quickly check whether a particular Internet-connected site is up and running. Since I've enabled ping (ICMP echo requests to be more precise) the computer, I can use ping as a simple check whether the machine is still powered on and that at least some kind of network communication still works.
To ping a host, you can use the following code:
using System;
using System.Net.NetworkInformation;
namespace PingTest
{
class Program
{
static void Main(string[] args)
{
PingHost("www.bing.com");
Console.ReadLine();
}
internal static bool PingHost(string hostname)
{
// create the ping object
Ping ping = new Ping();
int timeout = 5000; // five seconds
// ping the host and output status
PingReply reply = ping.Send(hostname, timeout);
Console.WriteLine("Response in " + reply.RoundtripTime + " ms: " + reply.Status);
// check to see if the ping was a success or not
bool success = (reply.Status == IPStatus.Success);
return success;
}
}
}
In this code, I'm using the built-in Ping class from the System.Net.NetworkInformation namespace.
Using this class is simple enough: just construct the class, give it some options, and send the ping. By looking at the response, you can find out whether the other end is still alive.
Hope this helps!