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

时间:2017-08-07 06:09:04

标签: c# console ping

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

我需要发送8个数据包,在我的命令promt中显示8个echo回复并带有统计信息。

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

3 个答案:

答案 0 :(得分:1)

在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);
    }
}

答案 1 :(得分:0)

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

然后,您可以使用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

输出应该是:

Exchange

答案 2 :(得分:0)

使用此示例:

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;