java程序如何获得 ntp时间
网上找到了
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.UnknownHostException;
public class TestNtp {
public static void main(String[] args){
int retry = 2;
int port = 123;
int timeout = 3000;
// get the address and NTP address request
//
InetAddress ipv4Addr = null;
try {
ipv4Addr = InetAddress.getByName("203.117.180.36");//更多NTP时间服务器参考附注
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
int serviceStatus = -1;
DatagramSocket socket = null;
long responseTime = -1;
try {
socket = new DatagramSocket();
socket.setSoTimeout(timeout); // will force the
// InterruptedIOException
for (int attempts = 0; attempts <= retry && serviceStatus != 1; attempts++) {
try {
// Send NTP request
//
byte[] data = new NtpMessage().toByteArray();
DatagramPacket outgoing = new DatagramPacket(data, data.length, ipv4Addr, port);
long sentTime = System.currentTimeMillis();
socket.send(outgoing);
// Get NTP Response
//
// byte[] buffer = new byte[512];
DatagramPacket incoming = new DatagramPacket(data, data.length);
socket.receive(incoming);
responseTime = System.currentTimeMillis() - sentTime;
double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
//这里要加2208988800,是因为获得到的时间是格林尼治时间,所以要变成东八区的时间,否则会与与北京时间有8小时的时差
// Validate NTP Response
// IOException thrown if packet does not decode as expected.
NtpMessage msg = new NtpMessage(incoming.getData());
double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2;
// System.out.print("===" + localClockOffset + ", responseTime= " + responseTime + "ms");
System.out.println("poll: NTP message : " + msg.toString());
serviceStatus = 1;
} catch (InterruptedIOException ex) {
// Ignore, no response received.
}
}
} catch (NoRouteToHostException e) {
System.out.println("No route to host exception for address: " + ipv4Addr);
} catch (ConnectException e) {
// Connection refused. Continue to retry.
e.fillInStackTrace();
System.out.println("Connection exception for address: " + ipv4Addr);
} catch (IOException ex) {
ex.fillInStackTrace();
System.out.println("IOException while polling address: " + ipv4Addr);
} finally {
if (socket != null)
socket.close();
}
// Store response time if available
//
if (serviceStatus == 1) {
System.out.println("responsetime=="+responseTime);
}
}
}
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.UnknownHostException;
public class TestNtp {
public static void main(String[] args){
int retry = 2;
int port = 123;
int timeout = 3000;
// get the address and NTP address request
//
InetAddress ipv4Addr = null;
try {
ipv4Addr = InetAddress.getByName("203.117.180.36");//更多NTP时间服务器参考附注
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
int serviceStatus = -1;
DatagramSocket socket = null;
long responseTime = -1;
try {
socket = new DatagramSocket();
socket.setSoTimeout(timeout); // will force the
// InterruptedIOException
for (int attempts = 0; attempts <= retry && serviceStatus != 1; attempts++) {
try {
// Send NTP request
//
byte[] data = new NtpMessage().toByteArray();
DatagramPacket outgoing = new DatagramPacket(data, data.length, ipv4Addr, port);
long sentTime = System.currentTimeMillis();
socket.send(outgoing);
// Get NTP Response
//
// byte[] buffer = new byte[512];
DatagramPacket incoming = new DatagramPacket(data, data.length);
socket.receive(incoming);
responseTime = System.currentTimeMillis() - sentTime;
double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
//这里要加2208988800,是因为获得到的时间是格林尼治时间,所以要变成东八区的时间,否则会与与北京时间有8小时的时差
// Validate NTP Response
// IOException thrown if packet does not decode as expected.
NtpMessage msg = new NtpMessage(incoming.getData());
double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2;
// System.out.print("===" + localClockOffset + ", responseTime= " + responseTime + "ms");
System.out.println("poll: NTP message : " + msg.toString());
serviceStatus = 1;
} catch (InterruptedIOException ex) {
// Ignore, no response received.
}
}
} catch (NoRouteToHostException e) {
System.out.println("No route to host exception for address: " + ipv4Addr);
} catch (ConnectException e) {
// Connection refused. Continue to retry.
e.fillInStackTrace();
System.out.println("Connection exception for address: " + ipv4Addr);
} catch (IOException ex) {
ex.fillInStackTrace();
System.out.println("IOException while polling address: " + ipv4Addr);
} finally {
if (socket != null)
socket.close();
}
// Store response time if available
//
if (serviceStatus == 1) {
System.out.println("responsetime=="+responseTime);
}
}
}
...全文
相关推荐
获取网络服务器时间.docx
**基础知识介绍**:了解基本的时间同步概念、NTP协议简介以及Java中处理日期和时间的基础知识。2. **代码实现**:展示如何使用Java编写程序来获取网络服务器上的时间。3.
实现NTP时间同步的Java工具类
本文还有配套的精品资源,点击获取 简介:时间同步在计算机网络中非常关键,尤其是在分布式系统和精确计时领域。本文详细讲解了如何编程实现与NTP服务器的时间同步,确保本地计算机时间的准确性。NTP协议通过发送和接收时间戳请求来计算传输延迟,从而实现高精度的时间同步。文章提供了一个简单的Java实现示例,并讨论了异常处理、多服务器支持、性能优化和日志记录等优化和扩展措施。 ...
网络时间协议(NTP)对时程序开发实战
NTP是一种分布式的时间同步协议,允许计算机通过网络同步到一个时间参考源。通常,这个参考源是一个更为精确的时间标准,如原子钟。NTP协议利用网络传输延迟和时间差来进行校准,即使在不稳定的网络条件下也能保证时间的准确性。在设计自定义的NTPClient类时,我们首先需要规划好类的结构以及每个部分的功能。NTPClient类的目的是为了简化与NTP服务器交互的过程,并且能够处理时间同步的需求。类结构应该包含以下几个主要部分:网络连接部分:负责与NTP服务器建立连接以及发送和接收数据。
NTP内网时间同步
Java是安卓开发的主要语言,因此可能涉及到使用Java代码来设置NTP服务器地址,并触发时间同步请求。例如,可以创建一个后台服务或定时任务,定期检查并更新系统时间。
获取NTP服务器时间,更改本地时间
**跨平台兼容性**:如果应用程序需要运行在不同的操作系统上,需要确保所使用的NTP库具有良好的跨平台兼容性。


