Question

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?

Was it helpful?

Solution

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 the NTP servers stopped supporting DAYTIME queries.

The NTP Project provides a sample code for an NTP client in Java here.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top