为什么 Ping 超时无法正常工作?

Why Ping timeout is not working correctly?

我有 5 台电脑,我想 ping 这台电脑是否可用。所以我正在使用 c# Ping class。有两台电脑可用,但当我对它们执行 ping 命令时,其他 3 台电脑已关闭我的程序等待 7 秒以内响应。

我只想检查 1000 毫秒和 returns OK 或 ERROR...

如何控制 ping 超时?

这是我的代码

        foreach (var item in listofpc)
        {
            Stopwatch timer = Stopwatch.StartNew();
            try
            {
                Ping myPing = new Ping();
                PingReply reply = myPing.Send(ServerName, 500);
                if (reply != null)
                {
                    timer.Stop();
                    TimeSpan timeTaken = timer.Elapsed;
                    Log.append("PING OK TimeTaken="+ timeTaken.ToString() + " Miliseconds", 50);
                }

            }
            catch (Exception ex)
            {
                timer.Stop();
                TimeSpan timeTaken = timer.Elapsed;
                Log.append("PING ERROR  TimeTaken=" +
                   timeTaken.ToString() + " Miliseconds \n" + ex.ToString(), 50);

            }
        }

但是当我查看我的日志时,我看到响应时间是 2 秒。为什么 ping 超时值不起作用?

有什么想法吗?

更新:原因:正如其他人所说,Ping 超时不起作用的最可能原因是 DNS 解析。对 getaddrinfo 的系统调用(Dns.GetHostAddresses 和 Ping - https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfo, https://docs.microsoft.com/en-us/dotnet/api/system.net.dns.gethostaddresses?view=netcore-3.1 使用的系统调用 - 类似于 Full Framework)不接受超时。因此,对下面代码的进一步改进是将 dns 查找与 ping 分开。首先使用类似于下面代码的超时方法进行查找,并且仅 ping IP 而不是主机名,并指定超时。

我过去 运行 遇到过类似的问题,我有一些代码可能有助于解决这个问题。我在这里编辑它,所以它可能不是 100% 正确,并且比您的需要复杂一点。你能试试这样的吗?

锤子:(下面还包含带有测试结果的完整代码)

private static PingReply ForcePingTimeoutWithThreads(string hostname, int timeout)
{
    PingReply reply = null;
    var a = new Thread(() => reply =  normalPing(hostname, timeout));
    a.Start();
    a.Join(timeout); //or a.Abort() after a timeout, but you have to take care of a ThreadAbortException in that case... brrr I like to think that the ping might go on and be successful in life with .Join :)
    return reply;
}

private static PingReply normalPing(string hostname, int timeout)
{
   try
   {
      return new Ping().Send(hostname, timeout);
   }
   catch //never do this kids, this is just a demo of a concept! Always log exceptions!
   {
      return null; //or this, in such a low level method 99 cases out of 100, just let the exception bubble up
    }
 }

这是一个完整的工作示例(Tasks.WhenAny 测试并在版本 4.5.2 中工作)。我还了解到,Tasks 的优雅带来了比我记忆中更显着的性能损失,但是 Thread.Join/Abort 对于大多数生产环境来说太残酷了。

using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        //this can easily be async Task<PingReply> or even made generic (original version was), but I wanted to be able to test all versions with the same code
        private static PingReply PingOrTimeout(string hostname, int timeOut)
        {
            PingReply result = null;
            var cancellationTokenSource = new CancellationTokenSource();
            var timeoutTask = Task.Delay(timeOut, cancellationTokenSource.Token);

            var actionTask = Task.Factory.StartNew(() =>
            {
                result = normalPing(hostname, timeOut);
            }, cancellationTokenSource.Token);

            Task.WhenAny(actionTask, timeoutTask).ContinueWith(t =>
            {
                cancellationTokenSource.Cancel();
            }).Wait(); //if async, remove the .Wait() and await instead!
            
            return result;
        }

        private static PingReply normalPing(string hostname, int timeout)
        {
            try
            {
                return new Ping().Send(hostname, timeout);
            }
            catch //never do this kids, this is just a demo of a concept! Always log exceptions!
            {
                return null; //or this, in such a low level method 99 cases out of 100, just let the exception bubble up
            }
        }

        private static PingReply ForcePingTimeoutWithThreads(string hostname, int timeout)
        {
            PingReply reply = null;
            var a = new Thread(() => reply =  normalPing(hostname, timeout));
            a.Start();
            a.Join(timeout); //or a.Abort() after a timeout... brrr I like to think that the ping might go on and be successful in life with .Join :)
            return reply;
        }

        static byte[] b = new byte[32];
        static PingOptions po = new PingOptions(64, true);
        static PingReply JimiPing(string hostname, int timeout)
        {
            try
            {
                return new Ping().Send(hostname, timeout, b, po);
            }
            catch //never do this kids, this is just a demo of a concept! Always log exceptions!
            {
                return null; //or this, in such a low level method 99 cases out of 100, just let the exception bubble up
            }
        }

        static void RunTests(Func<string, int, PingReply> timeOutPinger)
        {
            var stopWatch = Stopwatch.StartNew();
            var expectedFail = timeOutPinger("bogusdjfkhkjh", 200);
            Console.WriteLine($"{stopWatch.Elapsed.TotalMilliseconds} false={expectedFail != null}");
            stopWatch = Stopwatch.StartNew();
            var expectedSuccess = timeOutPinger("127.0.0.1", 200);
            Console.WriteLine($"{stopWatch.Elapsed.TotalMilliseconds} true={expectedSuccess != null && expectedSuccess.Status == IPStatus.Success}");
        }

        static void Main(string[] args)
        {
            RunTests(normalPing);
            RunTests(PingOrTimeout);
            RunTests(ForcePingTimeoutWithThreads);
            RunTests(JimiPing);
            
            Console.ReadKey(false);
        }
    }
}

我的一些测试结果:

>Running ping timeout tests timeout = 200. method=normal
>
> - host: bogusdjfkhkjh elapsed: 2366,9714 expected: false=False
> - host: 127.0.0.1 elapsed: 4,7249 expected: true=True
>
>Running ping timeout tests timeout = 200. method:ttl+donotfragment (Jimi)
>
> - host: bogusdjfkhkjh elapsed: 2310,836 expected: false actual: False
> - host: 127.0.0.1 elapsed: 0,7838 expected: true actual: True
>
>Running ping timeout tests timeout = 200. method:tasks
>
> - host: bogusdjfkhkjh elapsed: 234,1491 expected: false actual: False
> - host: 127.0.0.1 elapsed: 3,2829 expected: true=True
>
>Running ping timeout tests timeout = 200. method:threads
>
> - host: bogusdjfkhkjh elapsed: 200,5357 expected: false actual:False
> - host: 127.0.0.1 elapsed: 5,5956 expected: true actual: True

警告 对于任务版本,即使调用线程“未阻塞”,操作本身(在本例中为 ping)也可能会持续到实际超时为止。这就是为什么我建议也为 ping 命令本身设置超时。

更新 也在研究原因,但认为解决方法暂时可以帮助您。

新发现:

System.Net.NetworkInformation.Ping 的实施已通过
测试 框架 4.0/4.5.1/4.7.1,控制台和 Winforms 版本。

结果始终相同(如下所述)。

这是 IcmpSendEcho2Icmp6SendEcho2

.NET Framework Ping() 实现

同步版本(输出类型为Console,但不相关):

(The original version of this method does not return IPStatus. It returns a Class Object with full exception information. The Host Name or address is verified/translated with the DNS resolver:
IPAddress _HostIPAddress = Dns.GetHostAddresses(HostAddress).First(); which throws a SocketException if the Host is not found and a No such host is known notification.
The Result: BadDestination for an unknown host is set here just for this test).

static void Main(string[] args)
{
    List<string> HostAdrr = new List<string>() { "192.168.2.1", "192.168.2.201", 
                                                 "192.168.1.99", "200.1.1.1", 
                                                 "www.microsoft.com", "www.hfkhkhfhkf.com" };
    IPStatus _result;;
    foreach (string _Host in HostAdrr)
    {
        Stopwatch timer = Stopwatch.StartNew();
        _result = PingHostAddress(_Host, 1000);
        timer.Stop();
        Console.WriteLine("Host: {0}  Elapsed time: {1}ms  Result: {2}", _Host, timer.ElapsedMilliseconds, _result);
        Console.WriteLine();
    }
    Console.ReadLine();
}

public static IPStatus PingHostAddress(string HostAddress, int timeout)
{
    if (string.IsNullOrEmpty(HostAddress.Trim()))
        return IPStatus.BadDestination;

    byte[] buffer = new byte[32];
    PingReply iReplay = null;
    using (Ping iPing = new Ping())
    {
        try
        {
            //IPAddress _HostIPAddress = Dns.GetHostAddresses(HostAddress).First();
            iReplay = iPing.Send(HostAddress,
                                    timeout,
                                    buffer,
                                    new PingOptions(64, true));
        }
        catch (FormatException)
        {
            return IPStatus.BadDestination;
        }
        catch (NotSupportedException nsex)
        {
            throw nsex;
        }
        catch (PingException pex)
        {
            //Log/Manage pex
        }
        //catch (SocketException soex)
        //{
        //
        //}
        catch (Exception ex)
        {
            //Log/Manage ex
        }
        return (iReplay != null) ? iReplay.Status : IPStatus.BadDestination;
    }
}

异步版本使用.SendPingAsync()方法并具有通常的异步签名。

public async Task<IPStatus> PingHostAddressAsync(string HostAddress, int timeout)
{
    //(...)
    iReplay = await iPing.SendPingAsync(HostAddress,
                                        timeout,
                                        buffer,
                                        new PingOptions(64, false));
    //(...)
}

使用异步版本时结果不会改变。使用 Winforms 测试。不管有多少人想弄乱 UI.

如何解读结果:

参数:
- 由 Ping.Send() 方法解析的主机名。 (预先解析主机名不会改变结果)
- 超时: 1000 毫秒(还测试了 500 毫秒和 2000 毫秒)
- 缓冲区: 标准 32 字节
- TTL: 64
- 不要分段: 正确

Host: 192.168.2.1 => Reachable Host in the same network.
Host: 192.168.2.201 => Unreachable (off) Host in a reachable different subnet.
Host: 192.168.1.99 => Non existent Host in a reachable different network (hardware routed)
Host: 200.1.1.1 => Non existent Internet Address
Host: www.microsoft.com => Reachable existing resolved Internet Host Name
Host: www.hfkhkhfhkf.com => Non existent unresolvable Internet Host Name

Host: 192.168.2.1  Elapsed time: 4  Result: Success

Host: 192.168.2.201  Elapsed time: 991  Result: TimedOut

Host: 192.168.1.99  Elapsed time: 993  Result: TimedOut

Host: 200.1.1.1  Elapsed time: 997  Result: TimedOut

Host: www.microsoft.com  Elapsed time: 57  Result: Success

Host: www.hfkhkhfhkf.com  Elapsed time: 72  Result: BadDestination


As also noted by @PaulF in the comments, the only (persistent) anomaly is the first response if the Host is unreachable: it's always a bit shorter than the imposed timeout. But the Timeout is always respected (the Ping method always returns within the set time interval).

Ping 到 8.8.8.8 这样的 IP 地址绝对没问题,但是当 ping 到像 www.google.com 这样的 dns 地址时,随机超时。
我认为这些随机超时与 dns 解析有关,与 ping 超时无关

    private static bool DoPing()
    {
        try
        {
            using (System.Net.NetworkInformation.Ping ping = new Ping())
            {

                PingReply result = ping.Send("8.8.8.8", 500, new byte[32], new PingOptions { DontFragment = true, Ttl = 32 });

                if (result.Status == IPStatus.Success)
                    return true;
                return false;
            }
        }
        catch
        {
            return false;
        }
    }