为什么Ping超时无法正常工作? [英] Why Ping timeout is not working correctly?
问题描述
我有5台电脑,我想ping通这台电脑是否可用.所以我在用c#Ping类.当我对它们执行ping操作时,有两台电脑可用,而其他3台电脑则关闭,等待至少7秒以响应.
I have 5 pc and i want to ping this pc's are available or no. So I'm using c# Ping class. Two pc are available but the other 3 pc are closed when i ping them my program wait min 7 seconds for response.
我只想检查1000毫秒并返回OK或ERROR ...
I just want to check 1000 miliseconds and returns OK or ERROR...
如何控制ping超时?
How can i control ping timeout?
这是我的代码
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超时值不起作用?
But when i check my logs I saw response times are 2 seconds. Why ping timeout value is not working?
有什么主意吗?
推荐答案
我过去也遇到过类似的问题,并且我有一些代码可能有助于解决此问题.我在这里进行编辑,因此它可能仍不到100%正确,并且比您的需要还复杂.你可以尝试这样的事情吗?
I've run into similar issues in the past, and I have some code that might help in working around this issue. I am editing it here, so it might be less than 100% correct as is, and a bit more complicated than your needs. Can you try something like this?
锤子:(完整代码和测试结果也包括在下面)
The hammer: (full code with test results also included below)
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对于大多数生产环境来说太残酷了.
Here is a full working sample (Tasks.WhenAny tested and working in version 4.5.2). I also learned that the elegance of Tasks comes at a more significant performance hit than I remember, but Thread.Join/Abort are too brutal for most production environments.
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版本,即使调用线程是未阻止"的,操作本身(在这种情况下为ping)也可能会持续存在,直到它实际上超时为止.这就是为什么我建议也为ping命令本身设置一个超时的原因.
Caution For the Tasks version, even if the calling thread is "unblocked", the action itself, in this case the ping, might linger until it actually times out. That is why I suggest putting in a timeout for the ping command itself as well.
更新也研究了原因,但认为暂时解决方法对您有所帮助.
UPDATE Researching the why too, but thought a workaround would help you for now.
新发现:
- https://stackoverflow.com/a/34238797/8695782
- Ping timeout is unpredictable
这篇关于为什么Ping超时无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!