11 Mayıs 2021 Salı

NTPUDPClient Sınıfı

Giriş
Şu satırı dahil ederiz
<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.8.0</version>
</dependency>
Windows 10 ile NTP sunucusunu bulmak için şöyle  yaparız
w32tm /query /peers
Örnek 
Şöyle yaparız
NTPUDPClient ntpudpClient = new NTPUDPClient();
ntpudpClient.setDefaultTimeout(5000);

try {
  InetAddress inetAddress = InetAddress.getByName("192.168.43.32");
  TimeInfo timeInfo = ntpudpClient.getTime(inetAddress);

  TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
  Date date = timeStamp.getDate();
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
  simpleDateFormat.format(date);
} catch (UnknownHostException e) {
 ...
}
ntpudpClient.close();
TimeInfo ile şöyle yaparız
timeInfo.computeDetails();
if (timeInfo.getOffset() != null) {
  this.timeInfo = timeInfo;
  this.offset = timeInfo.getOffset();
}

// This system NTP time
TimeStamp systemNtpTime = TimeStamp.getCurrentTime();
System.out.println("System time:\t" + systemNtpTime + " " + systemNtpTime.toDateString());

// Calculate the remote server NTP time
long currentTime = System.currentTimeMillis();
TimeStamp atomicNtpTime = TimeStamp.getNtpTime(currentTime + offset).getTime()

System.out.println("Atomic time:\t" + atomicNtpTime + " " + atomicNtpTime.toDateString());
TimeInfo ile şöyle yaparız
TimeInfo info = client.getTime(hostAddr);
info.computeDetails(); // compute offset/delay if not already done
Long offsetValue = info.getOffset();
Long delayValue = info.getDelay();
String delay = (delayValue == null) ? "N/A" : delayValue.toString();
String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

System.out.println(" Roundtrip delay(ms)=" + delay
                + ", clock offset(ms)=" + offset); // offset in ms