import java.io.*;
import java.net.*;

public class TimeClientUDP {

	// The Time protocol defined in RFC 867 returns the server's time

    // The well known time port
	private static final int TIME_PORT = 13;

    public static void main(String[] args)  throws Exception{
		String hostName = null;
		try {
			hostName = args[0];
			System.out.println(getServerTime(hostName));
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host" + hostName);
			System.exit(1);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for "
								   + "the connection to:" + hostName);
			System.exit(1);
		} catch (ArrayIndexOutOfBoundsException aiobe) {
			System.err.println("wrong usage: enter hostname");
			System.exit(1);
		}
	}

	private static String getServerTime(String hostName)
		throws IOException, UnknownHostException {

	    DatagramSocket socket = new DatagramSocket();
        // send request
        byte[] buf = new byte[256];
        InetAddress address = InetAddress.getByName(hostName);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, TIME_PORT);
        socket.send(packet);

		// get response
        packet = new DatagramPacket(buf, buf.length);
		socket.receive(packet);
		BufferedReader input = new BufferedReader(new InputStreamReader(
				new ByteArrayInputStream(packet.getData())));

		 // display response
        String serverTime = input.readLine();
        socket.close();
		return serverTime;
	}
}

