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 ...
随机推荐
- IP访问频率限制不能用数组循环插入多个限制条件原因分析及解决方案
14.IP频率限制不能用数组循环插入多个限制条件原因分析及解决方案: define("RATE_LIMITING_ARR", array('3' => 3, '6' => ...
- 您厉害您赚得多:聪明投资者的聊天记录,雪球CEO的21条投资理念
3星|<您厉害您赚得多>:雪球创始人的投资理念.原则.技巧,及其在雪球上跟一些用户的互动的内容 作者是雪球创始人.CEO,全书基本是作者的一些投资理念+作者在雪球上跟用户的互动的内容,还有 ...
- Escaping Closures 两点:本质是生命周期标示符
1.block需要(拷贝)保存: 2.block引用的环境变量需要处理. 相当于oc中的copy block. Escaping Closures A closure is said to escap ...
- c#遍历注册表
--来自 https://blog.csdn.net/wenchangren/article/details/751863using System; using Microsoft.Win32; us ...
- (Entity framework 应用篇)把权限判断封装在数据库访问层
这里,我只是以一个例子,说一下简单权限控制,通过这个例子,大家可以设计庞大的权限管理层,把权限控制封装到数据库访问层,这样程序员就不用再写权限判断的代码了 首先,先看看我数据库DBContext的定义 ...
- CAD绘制一个对齐标注(com接口VB语言)
主要用到函数说明: _DMxDrawX::DrawDimAligned 绘制一个对齐标注.详细说明如下: 参数 说明 DOUBLE dExtLine1PointX 第一条界线开始点X值 DOUBLE ...
- Spring装配之——JAVA代码装配Bean
首先创建几个普通的JAVA对象,用于测试JAVA代码装配bean的功能. package soundsystemJava; //作为接口 定义了CD播放器对一盘CD所能进行的操作 public int ...
- 零基础转行Linux云计算运维工程师获得20万年薪的超级学习技巧
云计算概念一旦产生便一发不可收拾,成为移动互联网时代最为火热的行业之一.国内各大互联网公司例如阿里.腾讯.百度.网易等纷纷推出自己的云计算产品,3月10日,腾讯云0.01元投标时间更是让云计算在普罗大 ...
- 逆元Inv(模板+应用)
逆元: 如果满足公式,则有a 是 b的逆元同时b也是a的逆元. 逆元的应用: 设c为b在对m取余的意义下的逆元: 在求解公式 (a / b) % m的时候,如果b可能会非常的大,所以会出现爆精度的问题 ...
- RAID-独立磁盘冗余阵列
此文章理论部分内容大多数摘自网站 开心技术园 的一篇文章,但并做了一些修改与调整.理论部分原文链接:图文并茂 RAID 技术全解 – RAID0.RAID1.RAID5.RAID100-- 本文实验部 ...