Code example for DatagramSocket

Methods: close, receive, send, setSoTimeout

0
     * @param timeout network timeout in milliseconds. 
     * @return true if the transaction was successful. 
     */ 
    public boolean requestTime(String host, int timeout) {
        try { 
            DatagramSocket socket = new DatagramSocket();
            socket.setSoTimeout(timeout);
            InetAddress address = InetAddress.getByName(host);
            byte[] buffer = new byte[NTP_PACKET_SIZE];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
 
            // set mode = 3 (client) and version = 3 
            // mode is in low 3 bits of first byte 
            // version is in bits 3-5 of first byte 
            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
 
            // get current time and write it to the request packet 
            long requestTime = System.currentTimeMillis();
            // long requestTicks = SystemClock.elapsedRealtime(); 
            long requestTicks = System.nanoTime();
            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
 
            socket.send(request);
 
            // read the response 
            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);
            // long responseTicks = SystemClock.elapsedRealtime(); 
            long responseTicks = System.nanoTime();
            mNtpTimeRefSystemTime = System.currentTimeMillis();
 
            // long responseTime = requestTime + (responseTicks - requestTicks); 
            long responseTime = requestTime + (responseTicks - requestTicks) / NANO_IN_MILLI;
            socket.close();
 
            // extract the results 
            long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
            long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
            long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);