Thursday, May 13, 2010

C# Ping Status

One of the networks I manage needed a quick cheap solution for monitoring if a few servers were up. Came up with a C# Windows Service application that pings the servers every 15 minutes. If the ping fails for a system it will wait another 5 seconds and try it again. If both fail it will add it to a report that is emailed to the network admins. Below is the code for the test console app.

--------C# Test Console App Code-----------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Mail;
using System.Data;

namespace PING
class Program
static void Main(string[] args)
//Int for Counting Failed Pings
int pingFail = 0;

//String Builder for Email Message
StringBuilder stbFail = new StringBuilder();

//Hashtable for Server Name and IP Addresses
Hashtable servers = new Hashtable();

//Server Name is Key and IP Address is Value
servers.Add("Server1", "");
servers.Add("Server2", "");
servers.Add("Server3", "");
servers.Add("Server4", "");
servers.Add("Server5", "");
servers.Add("Server6", "");
servers.Add("Firewall1", "");
servers.Add("Firewall2", "");
servers.Add("Transwall1", "");

foreach (DictionaryEntry de in servers)
//Ping Server IP. If It Fails Ping Again Five Seconds Later
if (!PingCheck(de.Value.ToString()))
//Pausing for Five Seconds

//Second Ping Check on Failed IP
if (!PingCheck(de.Value.ToString()))
//Increment Verified Fail and Add Server Info to Report
stbFail.AppendLine(de.Key.ToString() + " at " + de.Value.ToString() + " is down");



//Email Failed Pings to Network Admin(s)
if (pingFail > 0)
//Create Mail Message and Send
MailAddress maFrom = new MailAddress("");
MailAddress maTo = new MailAddress("");
MailMessage message = new MailMessage(maFrom, maTo);
message.Subject = "Failed Ping Report";
message.IsBodyHtml = false;
message.Body = stbFail.ToString();
SmtpClient mail = new SmtpClient();
mail.Host = "";

static bool PingCheck(string strAddr)
bool pingStatus = false;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply replyPing = pingSender.Send(strAddr, timeout, buffer, options);

if (replyPing.Status == IPStatus.Success)
pingStatus = true;

return pingStatus;


No comments: