javasocketsprotocolsntp

Java HTTP client getting time from NTP server


I'm trying to write an HTTP client, and I need to get the time from an NTP server I found here: https://tf.nist.gov/tf-cgi/servers.cgi

This is my Java code:

String getTime(){
    String time = "";
    try{
        Socket timeSocket = new Socket("time-a-g.nist.gov",37);
        BufferedReader timeIn = new BufferedReader(new InputStreamReader(timeSocket.getInputStream()));
        time = timeIn.readLine();
        timeSocket.close();
        timeIn.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }
    return time;
}

I'm not getting any errors, but the string I'm getting back is null, can anyone help?


Solution

  • TCP (and UDP) port 37, which you are connecting to, is used for the TIME protocol (RFC 868). In this protocol, times are sent as a single binary 32bit integer in network byte order.

    UDP port 123 is used for the NTP protocol (RFCs 1059, 1119, 1305, 5905). In this protocol, times are sent as a series of binary messages.

    You can't read either type of data as text with BufferedReader.ReadLine().