为什么Ping超时工作不正常?

时间:2018-03-02 12:43:33

标签: c# timeout ping

我有5个电脑,我想ping这个电脑是可用的还是没有。所以我正在使用c#Ping类。有两个电脑可用,但是另外3个电脑关闭时,我的程序等待最少7秒钟的响应。

我只想检查1000毫秒并返回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超时值不起作用?

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

我过去遇到过类似的问题,我有一些代码可能有助于解决这个问题。我在这里编辑它,所以它可能不到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版本中测试并使用)。我还了解到,Task的优雅性比我记忆中的性能更受欢迎,但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

警告对于Tasks版本,即使调用线程是&#34; unblocked&#34;,操作本身(在本例中为ping)也可能会延迟,直到实际超时为止。这就是为什么我建议也为ping命令本身设置超时。

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

新发现:

答案 1 :(得分:1)

System.Net.NetworkInformation.Ping的实施已经过测试 框架4.0 / 4.5.1 / 4.7.1,控制台和Winforms版本
结果总是相同的(如下所述)
这是IcmpSendEcho2Icmp6SendEcho2

.NET Framework Ping()实施

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

  

(此方法的原始版本不会返回IPStatus   返回具有完整异常信息的类对象。主机名   或地址通过DNS解析器验证/翻译:
  IPAddress _HostIPAddress = Dns.GetHostAddresses(HostAddress).First();如果找不到主机并且没有这样的主机已知通知则会引发SocketException。<结果:BadDestination 对于一个未知的主机,这里只为此测试设置。)

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进行测试。无论有多少人试图弄乱用户界面。

如何解释结果:

参数:
- 通过Ping.Send()方法解析的主机名。 (预先解析主机名不会改变结果)
- 超时: 1000ms(也测试500ms和2000ms)
- 缓冲区:标准32字节
- TTL: 64
- 不要碎片:正确

  

主持人:192.168.2.1 =&gt;可在主机网络中使用主机   主持人:192.168.2.201 =&gt;无法访问(关闭)主机可达   不同的子网。
  主持人:192.168.1.99 =&gt;可访问的不同网络中不存在的主机(硬件路由)
  主持人:200.1.1.1 =&gt;不存在的互联网地址
  主持人:www.microsoft.com =&gt;可访问现有已解析的Internet主机名
  主持人:www.hfkhkhfhkf.com =&gt;不存在无法解析的Internet主机名

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


  

@PaulF在评论中也指出,唯一(持久的)异常   如果Host无法访问,它是第一个响应:它总是有点   比施加的超时短。但是Timeout始终受到尊重(Ping方法总是在设定的时间间隔内返回)。

答案 2 :(得分:0)

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;
        }
    }