using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace SeedServices
{
public static class PingServicecs
{
private const int TIME_OUT = 100;
private const int PACKET_SIZE = 512;
private const int TRY_TIMES = 2;
//检查时间的正则
private static Regex _reg = new Regex(@"时间=(.*?)ms", RegexOptions.Multiline | RegexOptions.IgnoreCase);
/// <summary>
/// 结果集
/// </summary>
/// <param name="stringcommandLine">字符命令行</param>
/// <param name="packagesize">丢包大小</param>
/// <returns></returns>
public static string LauchPing(string stringcommandLine,int packagesize)
{
Process process = new Process();
process.StartInfo.Arguments = stringcommandLine;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = "ping.exe";
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
return process.StandardOutput.ReadToEnd();//返回结果
}
/// <summary>
/// 转换字节
/// </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;
if (!int.TryParse(mc[0].Groups[1].Value, out int avg))
return 0.0F;
if (avg <= 0)
return 1024.0F;
return (float)packetSize / avg * 1000 / 1024;
}
/// <summary>
/// 通过Ip或网址检测调用Ping 返回 速度
/// </summary>,
/// <param name="strHost"></param>
/// <returns></returns>
public static string Test(string strHost,int trytimes,int PacketSize,int TimeOut)
{
return LauchPing(string.Format("{0} -n {1} -l {2} -w {3}", strHost, trytimes, PacketSize, TimeOut), PacketSize);
}
/// <summary>
/// 地址
/// </summary>
/// <param name="strHost"></param>
/// <returns></returns>
public static string Test(string strHost)
{
return LauchPing(string.Format("{0} -n {1} -l {2} -w {3}", strHost, TRY_TIMES, PACKET_SIZE, TIME_OUT), PACKET_SIZE);
}
}
}