如何在Java中访问NTP时钟 [英] How can I access NTP clock in java

查看:596
本文介绍了如何在Java中访问NTP时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java编写的分布式程序。我希望我的节点访问同步的物理时钟。

I have a distributed program written in java. I want my nodes access a synchronized physical clock.

我知道NTP是用于物理时钟同步的协议。我知道我可以通过sudo apt-get ntp将其安装在linux上。

I know NTP is a protocol for physical clock synchronization. I know that I can install it on linux by sudo apt-get ntp.

我的问题是安装它时,如何在Java程序中访问此同步时钟?我的意思是在计算机上安装ntp时会发生什么?我的系统 时钟会同步吗?

My question is when I install it, how can I access this synchronized clock in my java program? I mean what happens when I install ntp on my machine? my system clock will be sync?

谢谢:)

推荐答案

如果要访问NTP信息Java中,您可以创建符合NTP数据包格式(NTP RFC-1305)设置模式字段MODE_CLIENT(3)的UDP数据包,然后将数据包发送到NTP服务器端口123并侦听响应。

If want to access NTP info in Java you can create UDP packet conforming to the NTP packet format (NTP RFC-1305) setting mode field to MODE_CLIENT (3) then send packet to NTP server port 123 and listen for a response.

Apache Commons Net库已经有了使用此功能的框架

The Apache Commons Net library already has the framework to do this using only a few lines of code.

 NTPUDPClient client = new NTPUDPClient();
 client.open();
 InetAddress hostAddr = InetAddress.getByName("*insert-target-server-host-name.com*");
 TimeInfo info = client.getTime(hostAddr);
 info.computeDetails(); // compute offset/delay if not already done
 Long offsetValue = info.getOffset();
 Long delayValue = info.getDelay();
 String delay = (delayValue == null) ? "N/A" : delayValue.toString();
 String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

 System.out.println(" Roundtrip delay(ms)=" + delay
                + ", clock offset(ms)=" + offset); // offset in ms
 client.close();

请注意,本地时钟偏移(或时间漂移)是相对于本地时钟和

Note that the local clock offset (or time drift) is calculated with respect to the local clock and the NTP server's clock according to this standard NTP equation.

LocalClockOffset = ((ReceiveTimestamp - OriginateTimestamp) +
                             (TransmitTimestamp - DestinationTimestamp)) / 2

其中 OriginateTimestamp 是客户端发送的本地时间数据包(t1),
ReceiveTimestamp 是NTP服务器收到的时间请求(t2),
TransmitTimestamp 是服务器发送的时间回复(t3) ,而DestinationTimestamp是客户端在本地计算机(t4)上收到答复的时间。

Where OriginateTimestamp is the local time the client sent the packet (t1), ReceiveTimestamp is time request received by NTP server (t2), TransmitTimestamp is time reply sent by server (t3), and DestinationTimestamp is time at which reply received by client on local machine (t4).

有关完整代码,请参见客户端示例:

https://commons.apache.org/proper/commons-net/examples/ ntp / NTPClient.java

See client example for full code:
https://commons.apache.org/proper/commons-net/examples/ntp/NTPClient.java

这篇关于如何在Java中访问NTP时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆