Created
March 17, 2013 17:14
-
-
Save georgebyte/5182565 to your computer and use it in GitHub Desktop.
Java: Rdate (tool for querying the current time from a network server)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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