最近项目中涉及到一个时间验证的问题,需要根据当前时间来验证业务数据是否过期。所以直接写代码如下:

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网络时间的更多相关文章

  1. SYN2136型 北斗NTP网络时间服务器

    SYN2136型  北斗NTP网络时间服务器 北斗NTP网络时间服务器时间服务器使用说明视频链接: http://www.syn029.com/h-pd-109-0_310_36_-1.html 请将 ...

  2. SYN2102型 NTP网络时间服务器

    SYN2102型  NTP网络时间服务器   ntp主时钟服务器ntp时钟服务器厂商使用说明视频链接: http://www.syn029.com/h-pd-57-0_310_1_-1.html 请将 ...

  3. SYN2101型 NTP网络时间服务器

    SYN2101型  NTP网络时间服务器   时钟校准服务器时间 ntp服务器ntp时间校准服务器使用说明视频链接: http://www.syn029.com/h-pd-56-0_310_1_-1. ...

  4. Java获取各种常用时间方法大全

    Java获取各种常用时间方法大全 package cc.javaweb.test; Java中文网,Java获取各种时间大全 import java.text.DateFormat; import j ...

  5. java获取系统指定时间年月日

    java获取系统指定时间年月日 private String setDateTime(String falg) { Calendar c = Calendar.getInstance(); c.set ...

  6. GPS校时器,GPS时钟装置,NTP网络时间服务器

    GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间 ...

  7. Java获取当前的时间

    Java获取当前的时间 1.利用Java中的Calendar获取当前的时间 具体实现如下: /** * @Title:NowTime.java * @Package:com.you.model * @ ...

  8. 配置NTP网络时间自动校对系统时间和创建备份文件

    1 案例1:配置用户和组账号 1.1 问题 本例要求创建下列用户.组以及组的成员关系: 新建用户 alex,其用户ID为3456,密码是flectrag 创建一个名为 adminuser 的组 创建一 ...

  9. java 获取系统当前时间并格式化

      java 获取系统当前时间并格式化 CreateTime--2018年5月9日11:41:00 Author:Marydon 实现方式有三种 updateTime--2018年7月23日09点32 ...

随机推荐

  1. RTL Compiler之synthesis steps

    1 synthesis steps 1) Search Paths rc:/> set_attribute lib_search_path path / rc:/> set_attribu ...

  2. (转) SolrCloud之分布式索引及与Zookeeper的集成

    http://blog.csdn.net/ebay/article/details/46549481 作者:Wang, Josh 一.概述 Lucene是一个Java语言编写的利用倒排原理实现的文本检 ...

  3. 【Centos7】Tomcat安装及一个服务器配置多个Tomcat

    完成解压 参考 http://www.cnblogs.com/h--d/p/5074800.html https://www.cnblogs.com/tudou-22/p/9330875.html 步 ...

  4. .net 程序集加载,版本不匹配的解决方法

    经常有些时候,A.dll引用的是Microsoft.EntityFrameworkCore.dll version=1.0.0.0 publicKeyToken="adb9793829dda ...

  5. 1.git上手篇总结

    阅读 Git 原理详解及实用指南 记录 上手 1: Git 的最基本的工作模型 从 GitHub 把中央仓库 clone 到本地(使用命令: git clone) 把写完的代码提交(先用 git ad ...

  6. python 未知

    import timeimport requestsfrom bs4 import BeautifulSoupimport threading def format_str(s): return s. ...

  7. ganglia问题小结

    1.gmetad和rrdtool的关系 gmetad负责将轮询gmond拉取到的数据存入rrdtool的文件中,rrdtool 2.gemtad.conf ①命令:/usr/sbin/gmetad - ...

  8. Python 1 初识python

    1.Python介绍 Python是一种高级语言,与JAVA C# 等同.可以编写各种应用程序,每种语言都有其合适的应用场景.而Python 的优势在于更加人性化.简便的语法规则,以及针对各种具体场景 ...

  9. MySQL的各种网络IO超时的用法和实现

    2016-04-06 赵伟 数据库开发者 客户端C API 在C API中调用mysql_options()来设置mysql_init() 所创建的连接对象的属性,使用这三个选项可以设置连接超时和读写 ...

  10. [转]十五天精通WCF——第十四天 一起聊聊FaultException

     我们在玩web编程的时候,可能你会不经意的见到一些http500的错误,我想你应该不会陌生的,原因你应该也知道,服务器异常嘛, 这时候clr会把这个未处理的异常抛给iis并且包装成http500的错 ...