Th ecode below runs. I'm ping the Localhost using the name that gets returned from Dns.GetHostName(). YOu have to enter a return for the code to finish after the ping completes. the TTL is set to two so it will only go two hops. You
may need to increase the TTL when going through a multi-hop network.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string LocalHostName = Dns.GetHostName();
IP.PingIP(LocalHostName);
Console.ReadLine();
}
}
public class IP
{
public static void PingIP(string IP)
{
// Get an object that will block the main thread.
AutoResetEvent waiter = new AutoResetEvent(false);
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
options.Ttl = 2;
// When the PingCompleted event is raised,
// the PingCompletedCallback method is called.
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 0;
//PingReply reply = pingSender.Send(IP, timeout, buffer, options);
pingSender.SendAsync(IP, timeout, buffer, options, waiter);
}
private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
Console.WriteLine("Ping canceled.");
}
// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine("Ping failed:");
Console.WriteLine(e.Error.ToString());
}
PingReply reply = e.Reply;
DisplayReply(reply);
}
public static void DisplayReply(PingReply reply)
{
if (reply == null)
return;
Console.WriteLine("ping status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
return;
}
~IP()
{
}
}
}
jdweng