GetDate.java Source code

Java tutorial

Introduction

Here is the source code for GetDate.java

Source

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();
    }
}