连接到 NTP 服务器始终失败 (Java)
我刚刚学习如何用 Java 进行网络连接,第一个从 NTP 服务器获取时间的简单示例不断抛出 ConnectException。 我将复制并粘贴代码,但我感觉它一定是与代码无关的东西,因为该代码来自一本书。
import java.io.*;
import java.net.*;
public class AskTime {
public static void main(String a[]) throws Exception {
if(a.length != 1) {
System.out.println("your lame");
System.exit(0);
}
String machine = a[0];
final int daytimeport = 13;
Socket so = new Socket(machine,daytimeport);
BufferedReader br = new BufferedReader(new InputStreamReader(so.getInputStream() ) );
String time = br.readLine();
System.out.printf("%s says it is %s %n", machine, time);
}
}
我用来执行此操作的命令是:
java AskTime us.pool.ntp.org
更新: 阅读 msaeed 的建议后,我将端口更改为 123,现在正在使用告诉连接被拒绝而不是连接超时。 所以我认为 msaeed 是对的,有人知道我还需要沟通什么才能收到时间吗?
I'm just learning how to do networking in Java and the first simple example of getting the time from an NTP server keeps throwing a ConnectException. I'll copy and paste the code, but I have the feeling it must be something not code related since this code came out of a book.
import java.io.*;
import java.net.*;
public class AskTime {
public static void main(String a[]) throws Exception {
if(a.length != 1) {
System.out.println("your lame");
System.exit(0);
}
String machine = a[0];
final int daytimeport = 13;
Socket so = new Socket(machine,daytimeport);
BufferedReader br = new BufferedReader(new InputStreamReader(so.getInputStream() ) );
String time = br.readLine();
System.out.printf("%s says it is %s %n", machine, time);
}
}
The command I'm using to execute this is:
java AskTime us.pool.ntp.org
Update: After reading msaeed's advice I changed the port to 123 and am now being told connection refused instead of connection timed out. So I think msaeed is right, does anyone have any idea what else I need to communicate to receive a time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显然这段代码使用了旧的
DAYTIME
协议,该协议使用端口 13NTP
协议 使用端口 123,需要更多通信。 许多NTP
服务器停止支持DAYTIME
查询。NTP 项目提供了 Java 中
NTP
客户端的示例代码 在这里。So apparently this code uses the old
DAYTIME
protocol that uses port 13.NTP
protocol uses port 123 and requires a bit more communication. Many of theNTP
servers stopped supportingDAYTIME
queries.The NTP Project provides a sample code for an
NTP
client in Java here.msaeed 是对的。 您可以将代码与“time.nist.gov”等 DAYTIME 服务器一起使用 - 或从 此列表
更新 如果您的最终目标是与 NTP 服务器通信(而不是像您最初所说的那样使用套接字),您应该查看 Commons Net。 事实上,无论哪种方式,您都应该查看其源代码 - Commons Net 实现了相当多的网络协议。
msaeed is right. You can use your code with DAYTIME server like 'time.nist.gov' - or pick any other from this list
Update If your end goal is to communicate with NTP server (as opposed to play with sockets as you've said initially) you should look at Commons Net. In fact, you should look at its source either way - Commons Net implements quite a few network protocols.