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

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. 【sqli-labs】 less55 GET -Challenge -Union -14 queries allowed -Variation1 (GET型 挑战 联合查询 只允许14次查询 变化2)

    http://192.168.136.128/sqli-labs-master/Less-55/?id=1' 试了几次,整型带括号正常了 http://192.168.136.128/sqli-lab ...

  2. 阿里云ECS远程桌面连接失败

    管理=>本实例安全组=>配置规则=>配置3389端口

  3. MVC Ajax调用Action时-OnActionExecuting RedirectResult 无法跳转的处理办法

    public class BaseController : Controller { protected override void OnActionExecuting(ActionExecuting ...

  4. Oracle数据库的自动备份脚本

    @echo off echo ================================================ echo Windows环境下Oracle数据库的自动备份脚本 echo ...

  5. hdu2012 素数判定【C++】

    素数判定 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submis ...

  6. 协程,greenlet原生协程库, gevent库

    协程简介 协程(coroutine),又称为微线程,纤程,是一种用户级的轻量级线程.协程拥有自己的寄存器上下文和栈. 协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来时,恢复之前保存的上下文 ...

  7. Android一键换肤功能:一种简单的实现

     Android一键换肤功能:一种简单的实现 现在的APP开发,通常会提供APP的换肤功能,网上流传的换肤代码和实现手段过于复杂,这里有一个开源实现,我找了一大堆,发现这个项目相对较为简洁:htt ...

  8. python编码小记

    Python编码小记 标签(空格分隔): 编程 python 1.list类型remove()操作 列表对象执行remove()函数后,会自动退出循环,所以如果想利用一个单独的for循环删除列表中多个 ...

  9. 洛谷—— P2424 约数和

    https://www.luogu.org/problem/show?pid=2424 题目背景 Smart最近沉迷于对约数的研究中. 题目描述 对于一个数X,函数f(X)表示X所有约数的和.例如:f ...

  10. JVM内存管理和垃圾回收机制介绍

    http://backend.blog.163.com/blog/static/20229412620128233285220/     内存管理和垃圾回收机制是JVM最核心的两个组成部分,对其内部实 ...