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 ...
随机推荐
- java攻城师之路--复习java web之servlet
需要掌握的知识点:1.Servlet程序编写 ----- 生命周期2.ServletAPI Request Response 3.Cookie 和 Session Servlet 用来 动态web资源 ...
- linux下vim命令汇总
一. 进入vi的命令 vi filename : 打开或新建文件,并将光标置于第一行首 vi +n filename : 打开文件,并将光标置于第n行首 vi + filename : 打开文件,并将 ...
- 在Windows下安装Elasticsearch5.0
1.准备工作 安装和配置Java环境 2.下载 地址:https://www.elastic.co/downloads/elasticsearch 老版本:https://www.elastic.co ...
- DAMA
无论是小数据时代还是大数据时代,数据治理都是个非常重要的工作,数据质量问题是个非常普遍的问题.对于传统企业来说,核心业务还是流程驱动的,需要而且有条件把数据做准确,这就需要在数据管理上面下功夫. 介绍 ...
- Symbolicating Crash Reports With atos
地址:0x1000e4000 + 49116 = 0x00000001000effdc都是运行时地址: 0x1000e4000:基址偏移后的地址: 0x100000000: 共知基址:各个环境都知道, ...
- vue命令行创建运行工程
// install vue-cli 安装依赖包 npm install --g vue-cli// 使用vue-cli初始化项目 vue init webpack my-project// inst ...
- Django - Ajax基本内容整理
将原来的请求结果普通字符串,变更为类字典的字符串 从这段代码中,可以看到,对原有函数,进行了一个try ...except....操作,进行异常捕捉,将捕捉过程及结果,存入在初始化的字典中,将字典通过 ...
- cf 337 div2 c
C. Harmony Analysis time limit per test 3 seconds memory limit per test 256 megabytes input standard ...
- axios的基本概念和安装以及配置方法
ajax:异步请求,是一种无需再重新加载整个网页的情况下,能够更新部分网页的技术 axios:用于浏览器和node.js的基于promise的HTTP客户端 1.从浏览器制作XMLHttpReques ...
- 第四节:numpy之数组排序