在做系统对时的时候,需要使用到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:\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 }