快速判断ntp服务器的访问情况
我正在尝试创建一种方法来确定对 ntp 服务器的访问。我做了一个简单的方法,但是如果没有连接,那么它会等待很长时间才能得到答案 - 5秒。我检查了 5 个这样的服务器,例如 - time.nist.gov。我们必须等待很长时间。 问题:有没有一种简单的方法可以检查以避免等待这么长时间,大约1-2秒?
bool is_connection(char* url)
{
// time.nist.gov
return gethostbyname(url) != NULL;
}
I'm trying to create a method that determines access to the ntp server. I made a simple method, but if there is no connection, then it waits a long time for an answer - 5 seconds. I check 5 servers like this, for example - time.nist.gov. We have to wait a very long time.
Question: is there an easy way to check to avoid waiting so long, about 1-2 seconds?
bool is_connection(char* url)
{
// time.nist.gov
return gethostbyname(url) != NULL;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您应该在单独的线程中执行所有这些检查,并将它们连接起来以在单个请求中获取完整结果。
其次,NTP 使用 UDP,因此您无法检查端口(NTP 为 123)是否打开,因为 UDP 不是连接协议 - 即,除非服务器发回另一个数据报到,否则您没有传送结果确认您的数据报。使用 TCP,您可以“ping”端口来检查它是否打开,但在 UDP 中则不行。您需要深入研究 RFC 1305 才能进行检查。
解析名称不会帮助您检查它是否是有效且正在运行的 NTP 服务器。
无论如何,您的问题可以轻松解决,但解决方案很可能取决于您的操作系统(类型、版本……)、编译器(类型、版本、使用的 C++ 标准……)以及允许的 C++适合您情况的框架(开放式、受限式、便携式或非便携式……)。
我非常怀疑纯可移植 C++ 中是否存在有效的解决方案,特别是如果您坚持使用旧的 C++ 标准。有效的解决方案更有可能完全依赖于平台。
您应该精确您的工作环境以获得更精确的解决方案。
First, you should do all these checks in separated threads and join them to get the whole results in a single request.
Second, NTP uses UDP, so you can't check if the port (123 for NTP) is open or not, since UDP isn't a connected protocol - i.e. you don't have delivery results unless the server sends back another datagram to acknowledge your datagram. With TCP, you can "ping" a port to check if it's open, but not in UDP. You'll need to dive into RFC 1305 in order to be able to check that.
Resolving the name won't help you to check if it's a valid and working NTP server.
Anyway, your problem can be easily solved, but the solution is most likely dependent of your operating system (type, version, ...), your compiler (type, version, C++ standard used, ...), and the allowed C++ frameworks for your case (open bar, restricted, portable or not, ...).
I highly doubt that an EFFICIENT solution in pure portable C++ exists, in particular if you're stuck with old C++ standards. An efficient solution is more likely totally platform-dependent.
You should precise your working environment in order to get a more precise solution.