Free Information Technology Magazines and eBooks

Friday, June 26, 2009

C#: How to Ping a remote computer

Recently I was updating my free server monitoring software to include pre-checking of servers (if its online) before conducting resource information retrieval. To check if a server is indeed connected in the network, I included a Ping module that transmit a 32 bytes buffer to a remote computer (imitates windows ping command) and wait for reply.

.NET framework include a Ping class that allows an application to determine whether a remote computer is accessible over the network.

Here is the complete source code of my Ping module written in C#:

First include the following namespaces on the Using directives.

using System.Net.NetworkInformation;

Now insert this code for the Ping method.

static void Main(string[] args)
Console.Write("Enter the IP or Hostname to Ping: ");
string strhost = Console.ReadLine();
if (strhost.Length > 0)
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(strhost, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
Console.WriteLine("Ping was successful.");
Console.WriteLine("Ping failed.");
catch(Exception ex)

For more C# coding tips & tricks, subscribe now.


Sinistra said...

I've done the same, but at me it's a successful ping (to Google), even if the cable is unplugged. Google's good, it can be reached without Internet connection, or wtf.

Sinistra said...

Never mind, it works fine, thanks a lot.

Anonymous said...

You can download video tutorial for PING,IPsniffer,Network Status