Ping In C# .Net

This is probably old news to most people but I ended up googling for it so I'll record it here. Since .Net 2.0 there is a handy Ping class in the System.Net.NetworkInformation namespace that encapsulates - you guessed it - ping functionality. Here's some example code for performing a synchronous ping, check out this MSDN article for more detail and an asynchronous example.

using System.Net.NetworkInformation;

...

Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();

// 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;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);

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);
}

Jimmy

Related posts

Comments

Add comment


 

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

September 9. 2010 09:27

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010