【问题标题】:How to determine if ping reply has reached its timeout?如何确定 ping 回复是否已达到超时?
【发布时间】:2023-10-26 14:43:01
【问题描述】:

我需要确定是否发生超时并将条目保存到列表数组中。

这就是我 ping 并将往返值添加到一个列表数组的方式:

static void Ping()
{
    Console.Write(Environment.NewLine + "Start the test? (y/n): ");

    if (Console.ReadLine().ToLower() == "y")
    {
        List<int> lag = new List<int>();

        Console.WriteLine();

        for (int server = 1; server <= 139; server++)
        {
            string url = "world" + server.ToString() + ".runescape.com";

            Console.WriteLine("Checking world " + server + "...");

            Ping ping = new Ping();
            PingReply reply = ping.Send(url);

            lag.Add(int.Parse(reply.RoundtripTime.ToString()));
        }

    // ... More Code Here ...

    }
}

如何做到这一点?

【问题讨论】:

    标签: c# timeout console-application ping roundtrip


    【解决方案1】:

    查看状态属性

    reply.Status
    

    它返回一个IPStatus,它应该具有相应的状态。

    【讨论】:

    • @HelpNeeder 不错!很高兴我能帮上忙!
    【解决方案2】:

    您似乎需要使用 PingReply.Status 中的值来确定是否发生超时。 MSDN 文档指出:

    如果 Status 的值不是 Success,则不应使用这些值 由 RoundtripTime、Options 或 Buffer 属性返回。这 RoundtripTime 和 Buffer 属性将返回零,而 Options 属性将返回 null。

    http://msdn.microsoft.com/en-us/library/system.net.networkinformation.pingreply.status.aspx

    【讨论】: