Java获取NTP网络时间
最近项目中涉及到一个时间验证的问题,需要根据当前时间来验证业务数据是否过期。所以直接写代码如下:
new java.util.Date().getTime();
结果测试的时候出现了问题,怎么验证都是过期。后来发现是服务器主机时间不对。也就是说如果服务器时间不准确或者被篡改,那么验证这部分会出现问题。所以决定采用获取网络当前时间来代替获取系统当前时间。
搜索了一下,原来获取网络时间有一个协议:Network Time Protocol(NTP: 网络时间协议 )。
协议有了,那么java有没有相关实现呢。当然也有了。apache的commons-net包下面有ntp的实现。主要的类是:
org.apache.commons.net.ntp.NTPUDPClient 和 org.apache.commons.net.ntp.TimeInfo
看下用法,NTPUDPClient中有方法:
public TimeInfo getTime(InetAddress host, int port) throws IOException
public TimeInfo getTime(InetAddress host) throws IOException
第二个重载方法是用协议规范默认端口:123。
看下具体实现代码:
/***
* Retrieves the time information from the specified server and port and
* returns it. The time is the number of miliiseconds since
* 00:00 (midnight) 1 January 1900 UTC, as specified by RFC 1305.
* This method reads the raw NTP packet and constructs a <i>TimeInfo</i>
* object that allows access to all the fields of the NTP message header.
* <p>
* @param host The address of the server.
* @param port The port of the service.
* @return The time value retrieved from the server.
* @exception IOException If an error occurs while retrieving the time.
***/
public TimeInfo getTime(InetAddress host, int port) throws IOException
{
// if not connected then open to next available UDP port
if (!isOpen())
{
open();
} NtpV3Packet message = new NtpV3Impl();
message.setMode(NtpV3Packet.MODE_CLIENT);
message.setVersion(_version);
DatagramPacket sendPacket = message.getDatagramPacket();
sendPacket.setAddress(host);
sendPacket.setPort(port); NtpV3Packet recMessage = new NtpV3Impl();
DatagramPacket receivePacket = recMessage.getDatagramPacket(); /*
* Must minimize the time between getting the current time,
* timestamping the packet, and sending it out which
* introduces an error in the delay time.
* No extraneous logging and initializations here !!!
*/
TimeStamp now = TimeStamp.getCurrentTime(); // Note that if you do not set the transmit time field then originating time
// in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036".
message.setTransmitTime(now); _socket_.send(sendPacket);
_socket_.receive(receivePacket); long returnTime = System.currentTimeMillis();
// create TimeInfo message container but don't pre-compute the details yet
TimeInfo info = new TimeInfo(recMessage, returnTime, false); return info;
}
大概过程就是想目标网络地址发包来获取网络时间,具体细节由协议来规范。
所以我们还需要来确定网络地址,继续搜索,发现网络上有时间服务器,也叫授时服务器。我们的用智能手机的时间是不是通过这种方式来同步的呢?
找到了这样一些服务器地址:
中国时间网
国外的
NIST Internet Time Servers
代码例子:
public static void main(String[] args) {
try {
NTPUDPClient timeClient = new NTPUDPClient();
String timeServerUrl = "time-a.nist.gov";
InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);
TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(timeStamp.getDate()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
输出:2013-04-0211:01:08
Java获取NTP网络时间的更多相关文章
- SYN2136型 北斗NTP网络时间服务器
SYN2136型 北斗NTP网络时间服务器 北斗NTP网络时间服务器时间服务器使用说明视频链接: http://www.syn029.com/h-pd-109-0_310_36_-1.html 请将 ...
- SYN2102型 NTP网络时间服务器
SYN2102型 NTP网络时间服务器 ntp主时钟服务器ntp时钟服务器厂商使用说明视频链接: http://www.syn029.com/h-pd-57-0_310_1_-1.html 请将 ...
- SYN2101型 NTP网络时间服务器
SYN2101型 NTP网络时间服务器 时钟校准服务器时间 ntp服务器ntp时间校准服务器使用说明视频链接: http://www.syn029.com/h-pd-56-0_310_1_-1. ...
- Java获取各种常用时间方法大全
Java获取各种常用时间方法大全 package cc.javaweb.test; Java中文网,Java获取各种时间大全 import java.text.DateFormat; import j ...
- java获取系统指定时间年月日
java获取系统指定时间年月日 private String setDateTime(String falg) { Calendar c = Calendar.getInstance(); c.set ...
- GPS校时器,GPS时钟装置,NTP网络时间服务器
GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间 ...
- Java获取当前的时间
Java获取当前的时间 1.利用Java中的Calendar获取当前的时间 具体实现如下: /** * @Title:NowTime.java * @Package:com.you.model * @ ...
- 配置NTP网络时间自动校对系统时间和创建备份文件
1 案例1:配置用户和组账号 1.1 问题 本例要求创建下列用户.组以及组的成员关系: 新建用户 alex,其用户ID为3456,密码是flectrag 创建一个名为 adminuser 的组 创建一 ...
- java 获取系统当前时间并格式化
java 获取系统当前时间并格式化 CreateTime--2018年5月9日11:41:00 Author:Marydon 实现方式有三种 updateTime--2018年7月23日09点32 ...
随机推荐
- win10 打开chm文件内容空白如何解决
win10 打开chm文件内容空白如何解决 .CHM文件是非常常见的帮助文件格式.由于其便携性,很多小说或杂志也会采用chm格式.win7/win8.1/win10系统,由于采用了UAC,致使原本在x ...
- nested exception is java.io.FileNotFoundException: class path resource [jdbc.properties] cannot be opened because it does not exist
Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [j ...
- JS监听事件错误:Uncaught TypeError: xx(函数名)is not a function at HTMLInputElement.onclick
事件监听一直出错,提示已定义的函数名不是一个函数,折腾了好久才想到,原来是函数名和JS内部关键字重名造成的. 以前也遇到过这种情况,但因为发生的概率比较小,就没太在意,但是这次感觉这方面确实需要注意, ...
- Java笔记整理列表
整理Java相关知识点. 2018-11-20 1:Java入门学习 2:Java进阶
- 文艺平衡树(区间翻转)(Splay模板)
这篇blog写的吼啊 #include<cstdio> #include<iostream> #include<cstring> using namespace s ...
- CentOS7搭建KMS服务器
使用vlmcsd搭建KMS服务器 1.下载vlmcsd: wget https://github.com/Wind4/vlmcsd/releases/download/svn1111/binaries ...
- Luogu P2298 Mzc和男家丁的游戏
Mzc和男家丁的游戏 题目背景 mzc与djn的第二弹. 题目描述 mzc家很有钱(开玩笑),他家有n个男家丁(做过上一弹的都知道).他把她们召集在了一起,他们决定玩捉迷藏.现在mzc要来寻找他的男家 ...
- 【数值计算方法】二分法求根的C++简单实现
给定精确度ξ,用二分法求函数f(x)零点近似值的步骤如下: 1 确定区间[a,b],验证f(a)·f(b)<0,给定精确度ξ. 2 求区间(a,b)的中点c. 3 计算f(c). (1) 若f( ...
- Django REST framework 分页
三种分页:根据页码.根据索引.根据加密 http://www.xx.com/courses/?page=1&size=10 http://www.xx.com/courses/?offset= ...
- 举枪消灭"烂代码"的实战案例
前言 之前我写过一篇如何少写PHP "烂"代码 https://segmentfault.com/a/11...感觉很多新人对此不太理解.今天以打卡功能为例,去讲解其中的奥秘.那篇 ...