Mega Code Archive

 
Categories / Java / Network Protocol
 

Using Datagrams to Get the Date

import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class GetDate {   final static int PortDayTime = 13; // well-known daytime port   public static void main(String args[]) throws Exception {     byte msg[] = new byte[256];     DatagramSocket dgSocket = new DatagramSocket();     InetAddress destination = InetAddress.getByName("web.mit.edu");     DatagramPacket datagram = new DatagramPacket(msg, msg.length,         destination, PortDayTime);     dgSocket.send(datagram);     datagram = new DatagramPacket(msg, msg.length);     dgSocket.receive(datagram);     String received = new String(datagram.getData());     System.out.println("The time in Cambridge is now: " + received);     dgSocket.close();   } }