// // example of use of java.net.* classes: retrieve time/date from // remote host. // adapted from example in ch. 11 of _Exploring Java_, Niemeyer & Peck. // import java.net.* ; import java.io.* ; import java.util.* ; // // a DateAtHost object represents a Date (in Java format) as // reported by a remote host (via its port 37, an old // convention for reporting time/date). // public class DateAtHost extends Date { static int timePort = 37 ; // port usually used for reporting time/date static final long offset = 2208988800L ; // offset for converting between reporting // format (secs since 1/1/1900) and // Java format (millisecs since 1/1/1970). // (number is number of secs from 1/1/1900 to // 1/1/1970.) // usual constructor -- port defaults to 37. public DateAtHost(String host) throws IOException { this(host, timePort) ; } // general constructor -- specify hostname and port. public DateAtHost(String host, int port) throws IOException { // obtain time/date from remote host. Socket server = new Socket(host, port) ; DataInputStream din = new DataInputStream( server.getInputStream()) ; int time = din.readInt() ; server.close() ; // convert to Java format (first addition converts // unsigned int to signed long) and use to // reset Date object. setTime( (((1L << 32) + time) - offset) * 1000) ; } // ---- main --------------------------------------------------- // // command-line argument is (remote) hostname. // // examples: // java DateAtHost bianca.cs.trinity.edu // java DateAtHost rain.cise.ufl.edu // public static void main(String[] args) { if (args.length < 1) { System.out.println("Argument is hostname") ; System.exit(-1) ; } try { Date d = new DateAtHost(args[0]) ; System.out.println("The time and date at " + args[0] + " is " + d) ; System.out.println("Local time is " + new Date()) ; } catch (IOException e) { System.out.println("Error connecting to " + args[0]) ; } } }