如何使用 C# 获取 ping 统计信息?
How to get ping statistic with C#?
如何从 C# 获取 ping 统计信息?
我可以从 CMD ping
我也可以从 C# ping
var uri = "google.com";
var pingResult = new Ping().Send(uri);
https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping(v=vs.110).aspx
但在 ping 结果中我找不到 Ping 统计信息、近似往返、最小值、最大值。
有一些数据,但不是全部。
PingReply
class 中有 approximate round trip time。您可以使用它来进行往返。要获得最大值、最小值和平均值,只需发送多个数据包并对它们进行数学运算。这正是 ping
命令所做的,它发送了 4 个数据包并计算了这些数据包总和的最小最大值和平均值。
勾选MSDN doc
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)
{
//Here you get all your stats.
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);
}
如何从 C# 获取 ping 统计信息?
我可以从 CMD ping
我也可以从 C# ping
var uri = "google.com";
var pingResult = new Ping().Send(uri);
https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping(v=vs.110).aspx
但在 ping 结果中我找不到 Ping 统计信息、近似往返、最小值、最大值。 有一些数据,但不是全部。
PingReply
class 中有 approximate round trip time。您可以使用它来进行往返。要获得最大值、最小值和平均值,只需发送多个数据包并对它们进行数学运算。这正是 ping
命令所做的,它发送了 4 个数据包并计算了这些数据包总和的最小最大值和平均值。
勾选MSDN doc
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)
{
//Here you get all your stats.
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);
}