【问题标题】:How to run PING command and get ping host summary in C#?如何在 C# 中运行 PING 命令并获取 ping 主机摘要?
【发布时间】:2017-08-07 06:09:03
【问题描述】:

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

我需要发送 8 个数据包,将在我的命令提示符中显示 8 个回显回复和统计信息。

如何在 C# 控制台应用程序中做到这一点?

【问题讨论】:

    标签: c# console ping


    【解决方案1】:

    使用这个例子:

    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;
    

    【讨论】:

    • 抛出异常“拒绝访问”
    • @VenkateswaraReddy 将google.com 更改为您的主机地址。
    • 异常没有变化,和以前一样。显示为“拒绝访问”
    • @VenkateswaraReddy 看起来您有一些严格的系统策略或某种防病毒(防火墙),请尝试从命令行手动 ping
    • @VenkateswaraReddy 请分享异常消息的详细信息和抛出的行号。并尝试手动执行完整命令cmd.exe /c ping -n 8 your_host
    【解决方案2】:

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

    【讨论】:

    • 这没有回答 OP 的问题 - 他想 ping 一个远程主机。
    • 好的。让我们将第二行更改为:IPAddress address = IPAddress.Parse(yourREMOTE_IPAddress);
    • @PalBognar 你的回答是绝对正确的,但我需要显示回显回复和统计数据,但我的回答只显示统计数据。这就是问题
    【解决方案3】:

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

    【讨论】:

    • 我需要发送 4 个数据包,将收到 8 个数据包,否则会显示类似“ping 不成功”的错误消息
    • 使用-n 8 参数的ping 命令更改数据包大小。
    • @Dmitry 感谢您的评论。很有帮助。
    • 小心你的条款。数据包大小很容易被误解为数据包长度 (l)。 n 是数据包计数。
    • 但它会抛出一个错误“base = {“StandardOut 尚未重定向或进程尚未开始。”} 像这样......所以我该怎么办?
    猜你喜欢
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多