使用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 pingSender = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "test data abcabc"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 120; 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) { if (reply.RoundtripTime > 20) { sum++; }
} 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();
} } }
|