gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:51 25 4
gpt4 key购买 nike

我有 5 台电脑,我想 ping 这台电脑是否可用。所以我正在使用 c# Ping 类。有两台电脑可用,但当我对它们执行 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 超时值不起作用?

有什么想法吗?

最佳答案

更新:原因:正如其他人所说,Ping 超时不起作用的最可能原因是 DNS 解析。对 getaddrinfo 的系统调用(Dns.GetHostAddresses 和 Ping 使用的系统调用 - https://learn.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfohttps://learn.microsoft.com/en-us/dotnet/api/system.net.dns.gethostaddresses?view=netcore-3.1 - 类似于完整框架)不接受超时。因此,对下面代码的进一步改进是将 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

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

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

新发现:

关于c# - 为什么 Ping 超时无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com