Skip to content

Instantly share code, notes, and snippets.

@mnstrspeed
Created July 31, 2012 14:55
Show Gist options
  • Save mnstrspeed/3217611 to your computer and use it in GitHub Desktop.
Save mnstrspeed/3217611 to your computer and use it in GitHub Desktop.
Internet Connection Interruption Logger
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace InternetConnectionMonitor
{
internal class Program
{
public void Run(string path, int port)
{
this.StartServer(path, port);
Program.LogMessage(path, "# Started logging at {0}", DateTime.Now);
Console.CancelKeyPress += (sender, e) =>
Program.LogMessage(path, "# User exited application at {0}", DateTime.Now);
IPStatus lastStatus = IPStatus.Success;
DateTime startFailureTime = DateTime.Now; // To shut the compiler up
List<IPStatus> failures = new List<IPStatus>();
Ping ping = new Ping();
IPAddress target = IPAddress.Parse("8.8.8.8");
while (true)
{
PingReply reply = ping.Send(target);
if (reply.Status != lastStatus)
{
if (reply.Status == IPStatus.Success)
{
// Recovered from failure(s)
Program.LogMessage(path,
"{0}\t{1}\t{2}",
startFailureTime,
DateTime.Now - startFailureTime,
String.Join(", ", failures));
}
else
{
if (lastStatus == IPStatus.Success)
{
// First failure after success
startFailureTime = DateTime.Now;
failures.Clear();
}
if (!failures.Contains(reply.Status))
failures.Add(reply.Status);
}
}
lastStatus = reply.Status;
Thread.Sleep(15000);
}
}
private void StartServer(string path, int port)
{
if (!HttpListener.IsSupported)
Console.WriteLine("# HttpListener is not supported; web interface not available");
new Thread(() =>
{
HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add("http://*:" + port + "/");
httpListener.Start();
while (true)
{
HttpListenerContext context = httpListener.GetContext();
HttpListenerResponse response = context.Response;
using (StreamWriter writer = new StreamWriter(response.OutputStream))
using (StreamReader reader = new StreamReader(path))
{
while (reader.Peek() >= 0)
writer.WriteLine(reader.ReadLine());
}
}
}).Start();
}
private static void LogMessage(string path, string format, params object[] args)
{
using (StreamWriter writer = new StreamWriter(path, true))
{
Console.WriteLine(format, args);
writer.WriteLine(format, args);
}
}
public static void Main(string[] args)
{
string path = args.Length >= 1 ? args[0] : "log";
int port = args.Length >= 2 ? Int32.Parse(args[1]) : 1337;
new Program().Run(path, port);
Console.WriteLine("Program terminated");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment