import java.io.*; import java.net.*; import java.util.*; public class UdpDaytime { public static void main(String[] args) { String host; InetAddress hostAddress; byte[] outBuffer = new byte[1]; byte[] inBuffer = new byte[512]; DatagramPacket request; DatagramPacket reply; DatagramSocket timeSocket; // If number of args < 1, print usage. if (args.length < 1) { System.out.println("Usage: Daytime "); } else { try { // Get the host. host = args[0]; hostAddress = InetAddress.getByName(host); System.out.println("Getting daytime from " + hostAddress.toString() + " ..."); // Create the datagram socket. timeSocket = new DatagramSocket(); // Build the request and the reply buffer. request = new DatagramPacket(outBuffer, outBuffer.length, hostAddress, 13); reply = new DatagramPacket(inBuffer, inBuffer.length); // Send the requests and read the replies. try { // Set the socket timeout to 5 seconds. timeSocket.setSoTimeout(5 * 1000); // Send the request and get the reply. timeSocket.send(request); timeSocket.receive(reply); System.out.print("Reply received: " + new String(inBuffer, 0, reply.getLength())); } finally { timeSocket.close(); } } catch(Exception ex) { System.out.println(ex); } } System.exit(0); } }