@ryan.murray
You can get ping statistics with C# by using the System.Net.NetworkInformation
namespace, specifically the Ping
class. Here is an example code snippet that demonstrates how to ping a remote host and retrieve the statistics:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Net.NetworkInformation; class Program { static void Main() { string host = "www.google.com"; Ping ping = new Ping(); try { PingReply reply = ping.Send(host); if (reply.Status == IPStatus.Success) { Console.WriteLine("Ping to {0} was successful.", host); Console.WriteLine("Roundtrip time: {0} ms", reply.RoundtripTime); Console.WriteLine("Time to live: {0}", reply.Options.Ttl); Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment); } else { Console.WriteLine("Ping to {0} failed with status: {1}", host, reply.Status); } } catch (PingException e) { Console.WriteLine("An error occurred: {0}", e.Message); } } } |
In this code snippet, we first create an instance of the Ping
class and then use the Send
method to send a ping request to the specified host. We then check the Status
property of the PingReply
object to see if the ping was successful. If it was successful, we can retrieve various statistics such as roundtrip time, time to live, and whether the packet was fragmented.
Make sure to add the necessary exception handling to catch any errors that may occur during the ping request.