如何在 C# 中 运行 PING 命令并获取 ping 主机摘要?

How to run PING command and get ping host summary in C#?

我需要使用 C# 代码执行 PING 命令并获取 ping 主机的摘要。

我需要发送 8 个数据包,将在我的命令提示符中显示 8 个 echo 回复并进行统计。

如何在 C# 控制台应用程序中执行?

您可以使用 cmd.exe x.x.x.x -n 8 作为文件参数和 ping 作为命令参数来启动新的 Process

然后,您可以使用读取过程的 StreamReader 读取其结果数据' StandardOutput:

Process proc = new Process();
proc.StartInfo.FileName = @"C:\cmd.exe";
proc.StartInfo.Arguments = "ping xxx.xxx.xxx.xxx -n 8";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();

StreamReader reader;
reader = proc.StandardOutput;
proc.WaitForExit();

reader = proc.StandardOutput;
string result = reader.ReadToEnd();

请记得包括:using System.Diagnostics;

输出应该是:

Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms

Ping statistics for ::1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

查看 MSDN 中的这个示例:https://msdn.microsoft.com/en-us/library/hb7xxkfx(v=vs.110).aspx

public static void RemotePing ()
{
    // Ping's the local machine.
    Ping pingSender = new Ping ();
    IPAddress address = IPAddress.Parse("192.168.1.1"); //or IP address you'd like
    PingReply reply = pingSender.Send (address);

    if (reply.Status == IPStatus.Success)
    {
        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);
    }
    else
    {
        Console.WriteLine (reply.Status);
    }
}

使用这个例子:

var startInfo = new ProcessStartInfo( @"cmd.exe", "/c ping -n 8 google.com" )
{
     CreateNoWindow = true,
     UseShellExecute = false,
     RedirectStandardOutput = true
};

var pingProc = new Process { StartInfo = startInfo };
pingProc.Start();

pingProc.WaitForExit();

var result = pingProc.StandardOutput.ReadToEnd();

Console.WriteLine( result );
Console.ReadKey();

如果您需要了解这里的 ping 结果示例:

...
pingProc.WaitForExit();

var reader = pingProc.StandardOutput;
var regex = new Regex( @".+?\s+=\s+(\d+)(,|$)" );

var sent = 0;
var recieved = 0;
var lost = 0;

string result;
while ( ( result = reader.ReadLine() ) != null )
{
    if ( String.IsNullOrEmpty( result ) )
       continue;

    var match = regex.Matches( result );
    if ( match.Count != 3 )
       continue;

    sent = Int32.Parse( match[0].Groups[1].Value );
    recieved = Int32.Parse( match[1].Groups[1].Value );
    lost = Int32.Parse( match[2].Groups[1].Value );
}

var success = sent > 0 && sent == recieved && lost == 0;