using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.NetworkInformation;
namespace Ping
{
public partial class Form1 : Form
{
private int pingsSent;
AutoResetEvent resetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
}
private void btnPing_Click(object sender, EventArgs e)
{
pingsSent = 0;
txtResponse.Clear();
txtResponse.Text += "Pinging " + txtIP.Text + " with 32 bytes of data:\r\n\r\n";
SendPing();
}
private void SendPing()
{
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);
byte[] packetData = Encoding.ASCII.GetBytes("................................");
PingOptions packetOptions = new PingOptions(50, true);
pingSender.SendAsync(txtIP.Text, 5000, packetData, packetOptions, resetEvent);
}
private void pingSender_Complete(object sender, PingCompletedEventArgs e)
{
if (e.Cancelled)
{
txtResponse.Text += "Ping was canceled...\r\n";
((AutoResetEvent)e.UserState).Set();
}
else if (e.Error != null)
{
txtResponse.Text += "An error occured: " + e.Error + "\r\n";
((AutoResetEvent)e.UserState).Set();
}
else
{
PingReply pingResponse = e.Reply;
ShowPingResults(pingResponse);
}
}
public void ShowPingResults(PingReply pingResponse)
{
if (pingResponse == null)
{
txtResponse.Text += "There was no response.\r\n\r\n";
return;
}
else if (pingResponse.Status == IPStatus.Success)
{
txtResponse.Text += "Reply from " + pingResponse.Address.ToString() + ": bytes=" + pingResponse.Buffer.Length + " time=" + pingResponse.RoundtripTime + " TTL=" + pingResponse.Options.Ttl + "\r\n";
}
else
{
txtResponse.Text += "Ping was unsuccessful: " + pingResponse.Status + "\r\n\r\n";
}
pingsSent++;
if (pingsSent < 4)
{
SendPing();
}
}
}
}