1 16 package org.apache.commons.net; 17 18 import java.io.IOException ; 19 import java.net.DatagramPacket ; 20 import java.net.InetAddress ; 21 import java.util.Date ; 22 23 42 43 public final class TimeUDPClient extends DatagramSocketClient 44 { 45 46 public static final int DEFAULT_PORT = 37; 47 48 53 public static final long SECONDS_1900_TO_1970 = 2208988800L; 54 55 private byte[] __dummyData = new byte[1]; 56 private byte[] __timeData = new byte[4]; 57 58 71 public long getTime(InetAddress host, int port) throws IOException 72 { 73 long time; 74 DatagramPacket sendPacket, receivePacket; 75 76 sendPacket = 77 new DatagramPacket (__dummyData, __dummyData.length, host, port); 78 receivePacket = new DatagramPacket (__timeData, __timeData.length); 79 80 _socket_.send(sendPacket); 81 _socket_.receive(receivePacket); 82 83 time = 0L; 84 time |= (((__timeData[0] & 0xff) << 24) & 0xffffffffL); 85 time |= (((__timeData[1] & 0xff) << 16) & 0xffffffffL); 86 time |= (((__timeData[2] & 0xff) << 8) & 0xffffffffL); 87 time |= ((__timeData[3] & 0xff) & 0xffffffffL); 88 89 return time; 90 } 91 92 93 public long getTime(InetAddress host) throws IOException 94 { 95 return getTime(host, DEFAULT_PORT); 96 } 97 98 99 109 public Date getDate(InetAddress host, int port) throws IOException 110 { 111 return new Date ((getTime(host, port) - SECONDS_1900_TO_1970)*1000L); 112 } 113 114 115 116 public Date getDate(InetAddress host) throws IOException 117 { 118 return new Date ((getTime(host, DEFAULT_PORT) - 119 SECONDS_1900_TO_1970)*1000L); 120 } 121 122 } 123 124 | Popular Tags |