我需要使用C#代码执行PING命令,并获得ping主机的摘要。
我需要发送8个数据包,将在我的命令中显示8个回显答复与统计。
如何在C#控制台应用程序中实现?
发布于 2017-08-07 06:53:51
使用此示例:
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;发布于 2017-08-07 06:17:01
查看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);
}
}发布于 2017-08-07 06:15:18
您可以启动一个新的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 = 0mshttps://stackoverflow.com/questions/45540375
复制相似问题