| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- namespace HXX.Scanner.Biz
- {
- /// <summary>
- /// 获取网络状态
- /// </summary>
- public class biz_ping
- {
- /// <summary>
- /// 超时设置
- /// </summary>
- private const int TIME_OUT = 100;
- /// <summary>
- /// 包大小
- /// </summary>
- private const int PACKET_SIZE = 512;
- /// <summary>
- /// 重试次数
- /// </summary>
- private const int TRY_TIMES = 2;
- /// <summary>
- /// 对运行后结果的过滤规则的正则
- /// </summary>
- private static Regex _reg = new Regex(@"时间=(.*?)ms", RegexOptions.Multiline | RegexOptions.IgnoreCase);
- /// <summary>
- /// 调用系统ping命令
- /// </summary>
- /// <param name="strCommandline"></param>
- /// <param name="packetSize"></param>
- /// <returns></returns>
- private static float LaunchPing(string strCommandline, int packetSize)
- {
- Process proc = new Process();
- proc.StartInfo.Arguments = strCommandline;
- proc.StartInfo.UseShellExecute = false;
- proc.StartInfo.CreateNoWindow = true;
- proc.StartInfo.FileName = "ping.exe";
- proc.StartInfo.RedirectStandardInput = true;
- proc.StartInfo.RedirectStandardOutput = true;
- proc.StartInfo.RedirectStandardError = true;
- proc.Start();
- string strBuffer = proc.StandardOutput.ReadToEnd();
- proc.Close();
- //Console.WriteLine( strCommandline );
- //Console.WriteLine( strBuffer );
- return ParseResult(strBuffer, packetSize);
- }
- /// <summary>
- /// 根据ping的结果计时,估算网速
- /// </summary>
- /// <param name="strBuffer"></param>
- /// <param name="packetSize"></param>
- /// <returns></returns>
- private static float ParseResult(string strBuffer, int packetSize)
- {
- if (strBuffer.Length < 1) return 0.0F;
- MatchCollection mc = _reg.Matches(strBuffer);
- if (mc == null || mc.Count < 1 || mc[0].Groups == null) return 0.0F;
- int avg;
- if (!int.TryParse(mc[0].Groups[1].Value, out avg)) return 0.0F;
- if (avg <= 0) return 1024.0F;
- var result= (float)packetSize / avg * 1000 / 1024;
- return (float)result;
- }
- /// <param name="strHost">主机名或ip</param>
- /// <returns>kbps/s</returns>
- public static float Test(string strHost)
- {
- return LaunchPing(string.Format("{0} -n {1} -l {2} -w {3}", strHost, TRY_TIMES, PACKET_SIZE, TIME_OUT), PACKET_SIZE);
- }
- /// <param name="strHost">主机名或ip</param>
- /// <param name="PacketSize">发送测试包大小</param>
- /// <param name="TimeOut">超时</param>
- /// <param name="TryTimes">测试次数</param>
- /// <returns>kbps/s</returns>
- public static float Test(string strHost, int PacketSize, int TimeOut, int TryTimes)
- {
- return LaunchPing(string.Format("{0} -n {1} -l {2} -w {3}", strHost, TryTimes, PacketSize, TimeOut), PacketSize);
- }
- }
- }
|