import java.net.*;
import java.io.*;

        // Contact the daytime server running on hostname.
class UDPDaytimeClient {
    public UDPDaytimeClient(String hostname) throws UnknownHostException,
                                                    SocketException {
        // Obtain an InetAddress for the host.
        server = InetAddress.getByName(hostname);
        // Create a datagram socket for sending and receiving.
        socket = new DatagramSocket();
    }

    // Send a dummy packet to a UDP daytime service
    // and read the reply.
    public void run(){
        // The well-known port of the UDP daytime service.
        final int DaytimePort = 13;

        try{
            // Get the socket we are using.
            DatagramSocket socket = getSocket();
            // Get the address of the server.
            InetAddress server = getServer();

            // Create a datagram packet to send as a prompt.
            // Its contents are irrelevant.
            DatagramPacket prompt =
                new DatagramPacket(new byte[1],1,server,DaytimePort);
            // Create a buffer and packet for receiving the reply.
            final int bufferSpace = 80;
            byte[] replySpace = new byte[bufferSpace];
            DatagramPacket reply =
                new DatagramPacket(replySpace,replySpace.length);

            // Send the prompt.
            socket.send(prompt);
            // Receive the reply.
            socket.receive(reply);

            // Print out the reply and where it came from.
            System.out.println("Reply received from "+
                reply.getAddress().getHostAddress()+" port "+
                reply.getPort());

            System.out.write(replySpace,0,reply.getLength());
            socket.close();
        }
        catch(IOException e){
            System.err.println("IOException: "+e.getMessage());
        }
    }

    protected InetAddress getServer(){
        return server;
    }

    protected DatagramSocket getSocket(){
        return socket;
    }

    // Whom we are contacting.
    private final InetAddress server;
    // The socket we are using.
    private final DatagramSocket socket;
}

