码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-08-08 21:07:53      阅读:601      评论:0      收藏:0      [点我收藏+]

标签:

 

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

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

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

很详细,很有帮助。

  1 public class test {
  2 
  3     private static final NumberFormat numberFormat = new java.text.DecimalFormat("0.00");
  4     public static String ServerIP = "124.193.130.182";
  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:\t" + refAddr);
 82             TimeStamp refNtpTime = message.getReferenceTimeStamp();
 83             System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());
 84             // Originate Time is time request sent by client (t1)
 85             TimeStamp origNtpTime = message.getOriginateTimeStamp();
 86             System.out.println(" Originate Timestamp:\t" + 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:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());
 91             // Transmit time is time reply sent by server (t3)
 92             TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
 93             System.out.println(" Transmit Timestamp:\t" + 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:\t" + 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

标签:

原文地址:http://www.cnblogs.com/xiaoba1203/p/5741400.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!