【发布时间】:2017-08-07 06:09:03
【问题描述】:
我需要使用 C# 代码执行 PING 命令并获取 ping 主机的摘要。
我需要发送 8 个数据包,将在我的命令提示符中显示 8 个回显回复和统计信息。
如何在 C# 控制台应用程序中做到这一点?
【问题讨论】:
我需要使用 C# 代码执行 PING 命令并获取 ping 主机的摘要。
我需要发送 8 个数据包,将在我的命令提示符中显示 8 个回显回复和统计信息。
如何在 C# 控制台应用程序中做到这一点?
【问题讨论】:
使用这个例子:
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;
【讨论】:
google.com 更改为您的主机地址。
cmd.exe /c ping -n 8 your_host
看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);
}
}
【讨论】:
您可以使用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
【讨论】:
-n 8 参数的ping 命令更改数据包大小。