public boolean requestTime(String host,int timeout){
  DatagramSocket socket=null;
  try {
    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);
    buffer[0]=NTP_MODE_CLIENT | (NTP_VERSION << 3);
    long requestTime=System.currentTimeMillis();
    long requestTicks=SystemClock.elapsedRealtime();
    writeTimeStamp(buffer,TRANSMIT_TIME_OFFSET,requestTime);
    socket.send(request);
    DatagramPacket response=new DatagramPacket(buffer,buffer.length);
    socket.receive(response);
    long responseTicks=SystemClock.elapsedRealtime();
    long responseTime=requestTime + (responseTicks - requestTicks);
    long originateTime=readTimeStamp(buffer,ORIGINATE_TIME_OFFSET);
    long receiveTime=readTimeStamp(buffer,RECEIVE_TIME_OFFSET);
    long transmitTime=readTimeStamp(buffer,TRANSMIT_TIME_OFFSET);
    long roundTripTime=responseTicks - requestTicks - (transmitTime - receiveTime);
    mClockOffset=((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
    mNtpTime=responseTime + mClockOffset;
    mNtpTimeReference=responseTicks;
    mRoundTripTime=roundTripTime;
  }
 catch (  Exception e) {
    return false;
  }
 finally {
    if (socket != null) {
      socket.close();
    }
  }
  return true;
}

public boolean requestTime ( String host , int timeout ) { DatagramSocket socket = null ; try { 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 ) ; buffer [ 0 ] = NTP_MODE_CLIENT | ( NTP_VERSION << 3 ) ; long requestTime = System . currentTimeMillis ( ) ; long requestTicks = SystemClock . elapsedRealtime ( ) ; writeTimeStamp ( buffer , TRANSMIT_TIME_OFFSET , requestTime ) ; socket . send ( request ) ; DatagramPacket response = new DatagramPacket ( buffer , buffer . length ) ; socket . receive ( response ) ; long responseTicks = SystemClock . elapsedRealtime ( ) ; long responseTime = requestTime + ( responseTicks - requestTicks ) ; long originateTime = readTimeStamp ( buffer , ORIGINATE_TIME_OFFSET ) ; long receiveTime = readTimeStamp ( buffer , RECEIVE_TIME_OFFSET ) ; long transmitTime = readTimeStamp ( buffer , TRANSMIT_TIME_OFFSET ) ; long roundTripTime = responseTicks - requestTicks - ( transmitTime - receiveTime ) ; mClockOffset = ( ( receiveTime - originateTime ) + ( transmitTime - responseTime ) ) / 2 ; mNtpTime = responseTime + mClockOffset ; mNtpTimeReference = responseTicks ; mRoundTripTime = roundTripTime ; } catch ( Exception e ) { return false ; } finally { if ( socket != null ) { socket . close ( ) ; } } return true ; }
sends an sntp request to the given host and processes the response .
