using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.IO;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main(string[] args)
{
bool VerbindungOk = false;
int filter = 0;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
String format = "yyyy-MM-ddTHH:mm:ss";
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
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;
//Init
PingReply reply = pingSender.Send(args[0], timeout, buffer, options);
string LogFile = "Log_" + args[0] + ".txt";
if (reply.Status == IPStatus.Success)
{
Console.WriteLine(DateTime.Now.ToString(format) + " Start mit aktiver Verbindung");
VerbindungOk = true;
using (StreamWriter file = new StreamWriter(LogFile, true))
{
file.WriteLine(DateTime.Now.ToString(format) + " Start mit aktiver Verbindung");
}
}
else
{
Console.WriteLine(DateTime.Now.ToString(format) + " Start mit unterbrochener Verbindung");
VerbindungOk = false;
using (StreamWriter file = new StreamWriter(LogFile, true))
{
file.WriteLine(DateTime.Now.ToString(format) + " Start mit unterbrochener Verbindung");
}
}
while (true)
{
reply = pingSender.Send(args[0], timeout, buffer, options);
filter = reply.Status == IPStatus.Success ? 0 : filter++; //Verbindungsabbruch bei 5 oder mehr Fehlern am Stück
if (reply.Status == IPStatus.Success & !VerbindungOk)
{
Console.WriteLine(DateTime.Now.ToString(format) + " Verbindung wieder hergestellt");
VerbindungOk = true;
using (StreamWriter file = new StreamWriter(LogFile, true))
{
file.WriteLine(DateTime.Now.ToString(format) + " Verbindung wieder hergestellt");
}
}
else if (filter >= 5 & VerbindungOk)
{
Console.WriteLine(DateTime.Now.ToString(format) + " Verbindung unterbrochen");
VerbindungOk = false;
using (StreamWriter file = new StreamWriter(LogFile, true))
{
file.WriteLine(DateTime.Now.ToString(format) + " Verbindung unterbrochen");
}
}
else Console.Write(DateTime.Now.ToString(format) + " " + reply.Status + " \r");
Thread.Sleep(1000);
}
}
}
}