0%

使用C#的Ping类

使用Ping类检测网络丢包和延迟状况
MSDN有关Ping类的文档:https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping(v=vs.110).aspx
创建reply类后有以下几个描述

1
2
3
4
5
Console.WriteLine("答复的主机地址:" + reply.Address.ToString());
Console.WriteLine("往返时间:" + reply.RoundtripTime);
Console.WriteLine("生存时间(TTL):" + reply.Options.Ttl);
Console.WriteLine("是否控制数据包的分段:" + reply.Options.DontFragment);
Console.WriteLine("缓冲区大小:" + reply.Buffer.Length);

完整代码如下

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Text;
using System.Net.NetworkInformation;

namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string ipStr = "www.baidu.com";
//构造Ping实例
Ping pingSender = new Ping();
//Ping 选项设置
PingOptions options = new PingOptions();
options.DontFragment = true;
//测试数据
string data = "test data abcabc";
byte[] buffer = Encoding.ASCII.GetBytes(data);
//设置超时时间
int timeout = 120;
//调用同步 send 方法发送数据,将返回结果保存至PingReply实例
int sum = 0, sum2 = 0, per = 0;
PingReply reply;
for(int i=1;i<=100000;i++)
{
reply = pingSender.Send(ipStr, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
//假定20以内为正常反馈延时,可以跑几个看看正常应该是多少
if (reply.RoundtripTime > 20)
{
sum++;
//Console.WriteLine(reply.RoundtripTime+"ms");
}

}
else
sum2++;
if (i % 1000 == 0)
{
Console.Clear();

Console.WriteLine("进度:"+per + "%");
per += 1;
}
}

Console.WriteLine("共100000个数据包");
Console.WriteLine("延迟较大数:" + sum);
Console.WriteLine("丢包数:"+sum2);
double pee = sum2 / 100000.0 * 100;
Console.WriteLine("丢包比例:" + pee +"%");
Console.ReadKey();

}
}
}