Skip to content

Instantly share code, notes, and snippets.

@georgebyte
Created March 17, 2013 17:14
Show Gist options
  • Save georgebyte/5182565 to your computer and use it in GitHub Desktop.
Save georgebyte/5182565 to your computer and use it in GitHub Desktop.
Java: Rdate (tool for querying the current time from a network server)
import java.io.InputStream;
import java.net.Socket;
import java.util.Date;
public class Rdate {
public static void main(String[] args) {
try {
Socket s = new Socket("ntp1.arnes.si", 37);
InputStream input = s.getInputStream();
byte[] response = new byte[4];
input.read(response);
long seconds = bytesArrayToUnsignedLong(response);
seconds -= (long)22089888 * 100; //convert time to UNIX EPOCH
Date d = new Date(seconds * 1000);
System.out.println(d);
} catch (Exception ex) {
System.out.println("An error occured!");
ex.printStackTrace();
}
}
public static long bytesArrayToUnsignedLong(byte bytes[]) {
long result = 0;
for (int i = 0; i < bytes.length; i++) {
result += (long)(bytes[i] & 0xff) * Math.pow(256, bytes.length-i-1);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment