使用NTP获取网络时间-----java

摘要:
14InetAddresshostAddr=InetAddress.getByName(服务器IP);17processResponse(信息);18} catch(SocketExceptione){19e.printStackTrace();

在做系统对时的时候,需要使用到ntp来获取时间。

可以使用common-net包来获取ntp服务器的时间(即可以向那些标准时间服务器对时,也可以向自己设置好的ntp服务器进行对时)。

使用java获取ntp的时间(t1,t2,t3,t4)。下面是官网上给出的关于使用common-net关于ntp部分的使用例子。

如果要与指定服务器A对时(非NTP时间服务器),下面的代码也无需修改,只需要修改服务器A的ntp的配置文件,将服务器A设置为时钟服务器,并且不与其他时间服务器对时(设置为与自己对时),然后其他服务器就可以直接使用下面的代码,或者是ntpdate,ntpd都可以。

很详细,很有帮助。

  1 public class test {
  2 
  3     private static final NumberFormat numberFormat = new java.text.DecimalFormat("0.00");
  4     public static String ServerIP = "202.108.6.95";
  5     
  6     public static final  void main(String[] args) throws IOException 
  7     {
  8 
  9             NTPUDPClient client = new NTPUDPClient();
 10             // We want to timeout if a response takes longer than 10 seconds
 11             client.setDefaultTimeout(10000);
 12             try {
 13                 client.open();
 14                 InetAddress hostAddr = InetAddress.getByName(ServerIP);
 15                 System.out.println(" > " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
 16                 TimeInfo info = client.getTime(hostAddr);
 17                 processResponse(info);
 18             } catch (SocketException e) {
 19                 e.printStackTrace();
 20             }
 21             client.close();
 22     }
 23     
 24     
 25     public static  void processResponse(TimeInfo info) 
 26     {
 27             NtpV3Packet message = info.getMessage();
 28             int stratum = message.getStratum();
 29             String refType;
 30             if (stratum <= 0)
 31                 refType = "(Unspecified or Unavailable)";
 32             else if (stratum == 1)
 33                 refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
 34             else
 35                 refType = "(Secondary Reference; e.g. via NTP or SNTP)";
 36             // stratum should be 0..15...
 37             System.out.println(" Stratum: " + stratum + " " + refType);
 38             int version = message.getVersion();
 39             int li = message.getLeapIndicator();
 40             System.out.println(" leap=" + li + ", version="
 41                     + version + ", precision=" + message.getPrecision());
 42             System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
 43             int poll = message.getPoll();
 44             // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
 45             System.out.println(" poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll))
 46                     + " seconds" + " (2 ** " + poll + ")");
 47             double disp = message.getRootDispersionInMillisDouble();
 48             System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
 49                     + ", rootdispersion(ms): " + numberFormat.format(disp));
 50             int refId = message.getReferenceId();
 51             String refAddr = NtpUtils.getHostAddress(refId);
 52             String refName = null;
 53             if (refId != 0) {
 54                 if (refAddr.equals("127.127.1.0")) {
 55                     refName = "LOCAL"; // This is the ref address for the Local Clock
 56                 } else if (stratum  >= 2) {
 57                     // If reference id has 127.127 prefix then it uses its own reference clock
 58                     // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
 59                     // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
 60                     if (!refAddr.startsWith("127.127")) {
 61                         try {
 62                             InetAddress addr = InetAddress.getByName(refAddr);
 63                             String name = addr.getHostName();
 64                             if (name != null && !name.equals(refAddr))
 65                                 refName = name;
 66                         } catch (UnknownHostException e) {
 67                             // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
 68                             // ref not valid host maybe it's a reference clock name?
 69                             // otherwise just show the ref IP address.
 70                             refName = NtpUtils.getReferenceClock(message);
 71                         }
 72                     }
 73                 } else if (version  >= 3 && (stratum == 0 || stratum == 1)) {
 74                     refName = NtpUtils.getReferenceClock(message);
 75                     // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
 76                 }
 77                 // otherwise give up on naming the beast...
 78             }
 79             if (refName != null && refName.length()  > 1)
 80                 refAddr += " (" + refName + ")";
 81             System.out.println(" Reference Identifier:	" + refAddr);
 82             TimeStamp refNtpTime = message.getReferenceTimeStamp();
 83             System.out.println(" Reference Timestamp:	" + refNtpTime + "  " + refNtpTime.toDateString());
 84             // Originate Time is time request sent by client (t1)
 85             TimeStamp origNtpTime = message.getOriginateTimeStamp();
 86             System.out.println(" Originate Timestamp:	" + origNtpTime + "  " + origNtpTime.toDateString());
 87             long destTime = info.getReturnTime();
 88             // Receive Time is time request received by server (t2)
 89             TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
 90             System.out.println(" Receive Timestamp:	" + rcvNtpTime + "  " + rcvNtpTime.toDateString());
 91             // Transmit time is time reply sent by server (t3)
 92             TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
 93             System.out.println(" Transmit Timestamp:	" + xmitNtpTime + "  " + xmitNtpTime.toDateString());
 94             // Destination time is time reply received by client (t4)
 95             TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
 96             System.out.println(" Destination Timestamp:	" + destNtpTime + "  " + destNtpTime.toDateString());
 97             info.computeDetails(); // compute offset/delay if not already done
 98             Long offsetValue = info.getOffset();
 99             Long delayValue = info.getDelay();
100             String delay = (delayValue == null) ? "N/A" : delayValue.toString();
101             String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();
102             System.out.println(" Roundtrip delay(ms)=" + delay
103                     + ", clock offset(ms)=" + offset); // offset in ms
104     }
105 
106 }
 

免责声明:文章转载自《使用NTP获取网络时间-----java》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Samba服务器如何与Windows 95共享?Atitit 工程师程序员技术级别对应表与主要特征 P1--p6 说明 类别 职称 对应技术标志 P5 高级工程师 工程师类 一般四五年 P6 资深开发 工程师类 78年经历 P7 P7下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

iOS开发UI篇—UIPickerView控件简单介绍

iOS开发UI篇—UIPickerView控件简单介绍 一.UIPickerView 控件 1.简单介绍:  2.示例代码 TXViewController.m文件 1 // Created by 鑫 on 14-10-15. 2 3 // Copyright (c) 2014年 梁镋鑫. All rights reserved....

Linux下按程序查实时流量 network traffic

实然看到下载速度多达几M/s,但实际上并没有什么占用带宽的进程. 相查看每个程序占用的网络流量, 但系统自带的 System Monitor 只能查看全局的流量, 不能具体看某个程序的...... key words: network traffic, process specific, nethogs 工具: nethogs (要用sudo运行) D...

whl包构建

安装依赖 pip install whell pip install twine 参数对应 标注*号的为重要参数 描述性参数 —— 提供包信息,供PiPy识别管理 描述性参数,只是作为包的信息用的,没有特殊作用,可有可无。 参数 类型 说明 *name str 包名称 *version str 包版本 *author str 程序的作者...

IOS 特定于设备的开发:获取额外的设备信息

sysctl()和sysctlbyname()允许获取系统信息。这些标准的UNIX函数用于询问操作系统有关硬件和OS的详细信息。 这些常量使你能够检查核心信息,比如系统的CPU频率,可用的内存量等。它引入了一个UIDevice类,用于搜集系统信息,并通过一系列方法调用返回它。 每个型号都提供了独特的内置能力,准确知道你正在处理哪款iPhone有助于确定那个...

MySQL索引优化

一、单表 创建索引之前:type=ALL全表扫描,Extra里面的Using filesort(文件内部排序) 根据where后面的条件创建:CREATE INDEX idx_article_ccv ON article(category_id,comments,views);    可以看出type由ALL变成了range,但是Extra里面的Usi...

蓝桥---数的读法 (模拟)

Description Tom教授正在给研究生讲授一门关于基因的课程,有一件事情让他颇为头疼:一条染色体上有成千上万个碱基对,它们从0开始编号,到几百万,几千万,甚至上亿。比如说,在对学生讲解第1234567009号位置上的碱基时,光看着数字是很难准确的念出来的。所以,他迫切地需要一个系统,然后当他输入12 3456 7009时,会给出相应的念法:十二亿...