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", "192.168.xxx.xxx");
servers.Add("Server2", "192.168.xxx.xxx");
servers.Add("Server3", "192.168.xxx.xxx");
servers.Add("Server4", "192.168.xxx.xxx");
servers.Add("Server5", "192.168.xxx.xxx");
servers.Add("Server6", "192.168.xxx.xxx");
servers.Add("Firewall1", "192.168.xxx.xxx");
servers.Add("Firewall2", "192.168.xxx.xxx");
servers.Add("Transwall1", "192.168.xxx.xxx");


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
System.Threading.Thread.Sleep(5000);

//Second Ping Check on Failed IP
if (!PingCheck(de.Value.ToString()))
{
//Increment Verified Fail and Add Server Info to Report
pingFail++;
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("notifyingsystem@mydomain.edu");
MailAddress maTo = new MailAddress("guycomingintooffice@mydomain.edu");
MailMessage message = new MailMessage(maFrom, maTo);
message.Subject = "Failed Ping Report";
message.IsBodyHtml = false;
message.Body = stbFail.ToString();
SmtpClient mail = new SmtpClient();
mail.Host = "smtp.mydomain.edu";
mail.Send(message);
}
}

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: