Preciso que meu sistema utilize a hora de um servidor NTP.
Segui um trecho de código utilizando jakarta commons.net
NTPUDPClient ntp = new NTPUDPClient();
ntp.open();
TimeInfo time = ntp.getTime(InetAddress.getByName("http://br.pool.ntp.org"));
ntp.close();
Date hora = new Date(time.getReturnTime());
E o erro que aparece no Console:
Exception in thread “main” java.net.UnknownHostException: http://br.pool.ntp.org: http://br.pool.ntp.org
at java.net.InetAddress.getAllByName0(InetAddress.java:1128)
at java.net.InetAddress.getAllByName0(InetAddress.java:1098)
at java.net.InetAddress.getAllByName(InetAddress.java:1061)
at java.net.InetAddress.getByName(InetAddress.java:958)
at TesteDatas.main(TesteDatas.java:18)
Alguém tem algum exemplo ? Ou sabe o que está errado?
Agradeço a atenção de todos.
Kra, o NTP é um simples servidor UDP que trata um tipo de mensagens específicas segundo a documentação do NTP…
Você nao pode colocar “http”. Pois ele irá usar o protocolo TCP. Nada a ver. Tenta colocar apenas o nome ali ou ip ali. o InetAddress é uma referencia ao IP, ou a um endereco. Não envolve protocolo nenhum.
O ideal, para testar, é colocar apenas o IP. dá um ping no pool que vc tá usando e coloca o IP. depois tenta com o nome…
flw
Então tentei pelo IP e não funcionou o problema está na linha:
TimeInfo time = ntp.getTime(InetAddress.getByName("146.164.48.5"));
Se alguem souber algum outro servidor ntp agradeço.
Alguém mais tem dicas?
Abraço a todos… Paz.
Kra, tem o da Microsoft. time.windows.com
Mais a noite, testarei. Vc viu se é assim que se captura o ntp mesmo??? É usando esse TimeInfo?
Mais tarde te dou um retorno…
flw
Kra, é necessário tratar o retorno deles. Segue uma classe que funciona com certeza. Testei tranquilo.
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.NtpUtils;
import org.apache.commons.net.ntp.NtpV3Packet;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.commons.net.ntp.TimeStamp;
public final class NTPClient {
private static final NumberFormat numberFormat = new java.text.DecimalFormat("0.00");
public static void processResponse(TimeInfo info) {
NtpV3Packet message = info.getMessage();
int stratum = message.getStratum();
String refType;
if (stratum <= 0)
refType = "(Unspecified or Unavailable)";
else if (stratum == 1)
refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
else
refType = "(Secondary Reference; e.g. via NTP or SNTP)";
System.out.println(" Stratum: " + stratum + " " + refType);
int version = message.getVersion();
int li = message.getLeapIndicator();
System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision());
System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
int poll = message.getPoll();
System.out.println(" poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")");
double disp = message.getRootDispersionInMillisDouble();
System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble()) + ", rootdispersion(ms): " + numberFormat.format(disp));
int refId = message.getReferenceId();
String refAddr = NtpUtils.getHostAddress(refId);
String refName = null;
if (refId != 0) {
if (refAddr.equals("127.127.1.0")) {
refName = "LOCAL";
} else if (stratum >= 2) {
if (!refAddr.startsWith("127.127")) {
try {
InetAddress addr = InetAddress.getByName(refAddr);
String name = addr.getHostName();
if (name != null && !name.equals(refAddr))
refName = name;
} catch (UnknownHostException e) {
refName = NtpUtils.getReferenceClock(message);
}
}
} else if (version >= 3 && (stratum == 0 || stratum == 1)) {
refName = NtpUtils.getReferenceClock(message);
}
}
if (refName != null && refName.length() > 1)
refAddr += " (" + refName + ")";
System.out.println(" Reference Identifier:\t" + refAddr);
TimeStamp refNtpTime = message.getReferenceTimeStamp();
System.out.println(" Reference Timestamp:\t" + refNtpTime + " " + refNtpTime.toDateString());
TimeStamp origNtpTime = message.getOriginateTimeStamp();
System.out.println(" Originate Timestamp:\t" + origNtpTime + " " + origNtpTime.toDateString());
long destTime = info.getReturnTime();
TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
System.out.println(" Receive Timestamp:\t" + rcvNtpTime + " " + rcvNtpTime.toDateString());
TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + " " + xmitNtpTime.toDateString());
TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
System.out.println(" Destination Timestamp:\t" + destNtpTime + " " + destNtpTime.toDateString());
info.computeDetails();
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);
}
public static final void main(String[] args)
{
NTPUDPClient client = new NTPUDPClient();
args = new String[]{"br.pool.ntp.org","south-america.pool.ntp.org"};
client.setDefaultTimeout(10000);
try {
client.open();
for (int i = 0; i < args.length; i++)
{
System.out.println();
try {
InetAddress hostAddr = InetAddress.getByName(args[i]);
System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
TimeInfo info = client.getTime(hostAddr);
processResponse(info);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} catch (SocketException e) {
e.printStackTrace();
}
client.close();
}
}
É só adaptar agora. Flw