2

从 C# 控制台应用程序中,我打开了命令提示符并检查了 ping 实用程序。

string aptracommand;
aptracommand = "/C ping 10.38.2.73";
Process.Start(@"cmd",aptracommand);

现在,我需要应用一个条件语句,如果 ping 请求超时,那么它应该说“无法连接”,如果它能够 ping,那么需要显示“服务器已启动”

4

3 回答 3

9

为此,您可以使用 Ping 类。如下所述:

using System.Net.NetworkInformation;

var ping = new Ping();
var reply = ping.Send("10.38.2.73", 60 * 1000); // 1 minute time out (in ms)
if (reply.Status == IPStatus.Success)
{
   Console.WriteLine("Server is up");
}
else
{
   Console.WriteLine("Server is down");
}

您可以减少超时值以快速检查服务器是启动还是关闭。

于 2012-09-27T12:06:43.087 回答
2

改用这个

Ping pingSender = new Ping ();
byte[] data = Encoding.ASCII.GetBytes ("test");
int timeout = 100;
PingReply reply = pingSender.Send("127.0.0.1", timeout, data);
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);
}
于 2012-09-27T12:08:01.510 回答
0

我认为您需要捕获输出,检查是否存在超时字符串,然后据此做出决定。

捕获输出

于 2012-09-27T12:06:18.300 回答