Search in sources :

Example 51 with DatagramSocket

use of java.net.DatagramSocket in project actor-platform by actorapp.

the class SntpClient method requestTime.

/**
     * Sends an SNTP request to the given host and processes the response.
     *
     * @param host    host name of the server.
     * @param timeout network timeout in milliseconds.
     * @return true if the transaction was successful.
     */
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);
        // 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();
        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 responseTime = requestTime + (responseTicks - requestTicks);
        // extract the results
        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);
        // receiveTime = originateTime + transit + skew
        // responseTime = transmitTime + transit - skew
        // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
        //             = ((originateTime + transit + skew - originateTime) +
        //                (transmitTime - (transmitTime + transit - skew)))/2
        //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
        //             = (transit + skew - transit + skew)/2
        //             = (2 * skew)/2 = skew
        mClockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
        // if (false) Log.d(TAG, "round trip: " + roundTripTime + " ms");
        // if (false) Log.d(TAG, "clock offset: " + clockOffset + " ms");
        // save our results - use the times on this side of the network latency
        // (response rather than request time)
        mNtpTime = responseTime + mClockOffset;
        mNtpTimeReference = responseTicks;
        mRoundTripTime = roundTripTime;
    } catch (Exception e) {
        return false;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
    return true;
}
Also used : DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) InetAddress(java.net.InetAddress)

Example 52 with DatagramSocket

use of java.net.DatagramSocket in project ribbon by Netflix.

the class UdpClientTest method choosePort.

public int choosePort() throws SocketException {
    DatagramSocket serverSocket = new DatagramSocket();
    int port = serverSocket.getLocalPort();
    serverSocket.close();
    return port;
}
Also used : DatagramSocket(java.net.DatagramSocket)

Example 53 with DatagramSocket

use of java.net.DatagramSocket in project android_frameworks_base by ParanoidAndroid.

the class DnsPinger method handleMessage.

@Override
public void handleMessage(Message msg) {
    switch(msg.what) {
        case ACTION_PING_DNS:
            DnsArg dnsArg = (DnsArg) msg.obj;
            if (dnsArg.seq != mCurrentToken.get()) {
                break;
            }
            try {
                ActivePing newActivePing = new ActivePing();
                InetAddress dnsAddress = dnsArg.dns;
                newActivePing.internalId = msg.arg1;
                newActivePing.timeout = msg.arg2;
                newActivePing.socket = new DatagramSocket();
                // Set some socket properties
                newActivePing.socket.setSoTimeout(SOCKET_TIMEOUT_MS);
                // Try to bind but continue ping if bind fails
                try {
                    newActivePing.socket.setNetworkInterface(NetworkInterface.getByName(getCurrentLinkProperties().getInterfaceName()));
                } catch (Exception e) {
                    loge("sendDnsPing::Error binding to socket " + e);
                }
                newActivePing.packetId = (short) sRandom.nextInt();
                byte[] buf = mDnsQuery.clone();
                buf[0] = (byte) (newActivePing.packetId >> 8);
                buf[1] = (byte) newActivePing.packetId;
                // Send the DNS query
                DatagramPacket packet = new DatagramPacket(buf, buf.length, dnsAddress, DNS_PORT);
                if (DBG) {
                    log("Sending a ping " + newActivePing.internalId + " to " + dnsAddress.getHostAddress() + " with packetId " + newActivePing.packetId + ".");
                }
                newActivePing.socket.send(packet);
                mActivePings.add(newActivePing);
                mEventCounter++;
                sendMessageDelayed(obtainMessage(ACTION_LISTEN_FOR_RESPONSE, mEventCounter, 0), RECEIVE_POLL_INTERVAL_MS);
            } catch (IOException e) {
                sendResponse(msg.arg1, -9999, SOCKET_EXCEPTION);
            }
            break;
        case ACTION_LISTEN_FOR_RESPONSE:
            if (msg.arg1 != mEventCounter) {
                break;
            }
            for (ActivePing curPing : mActivePings) {
                try {
                    /** Each socket will block for {@link #SOCKET_TIMEOUT_MS} in receive() */
                    byte[] responseBuf = new byte[2];
                    DatagramPacket replyPacket = new DatagramPacket(responseBuf, 2);
                    curPing.socket.receive(replyPacket);
                    // Check that ID field matches (we're throwing out the rest of the packet)
                    if (responseBuf[0] == (byte) (curPing.packetId >> 8) && responseBuf[1] == (byte) curPing.packetId) {
                        curPing.result = (int) (SystemClock.elapsedRealtime() - curPing.start);
                    } else {
                        if (DBG) {
                            log("response ID didn't match, ignoring packet");
                        }
                    }
                } catch (SocketTimeoutException e) {
                // A timeout here doesn't mean anything - squelsh this exception
                } catch (Exception e) {
                    if (DBG) {
                        log("DnsPinger.pingDns got socket exception: " + e);
                    }
                    curPing.result = SOCKET_EXCEPTION;
                }
            }
            Iterator<ActivePing> iter = mActivePings.iterator();
            while (iter.hasNext()) {
                ActivePing curPing = iter.next();
                if (curPing.result != null) {
                    sendResponse(curPing.internalId, curPing.packetId, curPing.result);
                    curPing.socket.close();
                    iter.remove();
                } else if (SystemClock.elapsedRealtime() > curPing.start + curPing.timeout) {
                    sendResponse(curPing.internalId, curPing.packetId, TIMEOUT);
                    curPing.socket.close();
                    iter.remove();
                }
            }
            if (!mActivePings.isEmpty()) {
                sendMessageDelayed(obtainMessage(ACTION_LISTEN_FOR_RESPONSE, mEventCounter, 0), RECEIVE_POLL_INTERVAL_MS);
            }
            break;
        case ACTION_CANCEL_ALL_PINGS:
            for (ActivePing activePing : mActivePings) activePing.socket.close();
            mActivePings.clear();
            break;
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InetAddress(java.net.InetAddress) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 54 with DatagramSocket

use of java.net.DatagramSocket in project pinpoint by naver.

the class UdpSocketTest method createUdpSocket.

//    @Test
public void createUdpSocket() throws IOException {
    DatagramSocket so = new DatagramSocket();
    //        so.bind(new InetSocketAddress("localhost", 8081));
    //        DatagramSocket receiver = new DatagramSocket(new InetSocketAddress("localhost", 8082));
    //        receiver.bind(new InetSocketAddress("localhost", 8082));
    so.connect(new InetSocketAddress("localhost", 8082));
    so.send(new DatagramPacket(new byte[10], 10));
    //        receiver.receive(newDatagramPacket(1000));
    so.close();
}
Also used : DatagramSocket(java.net.DatagramSocket) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(java.net.DatagramPacket)

Example 55 with DatagramSocket

use of java.net.DatagramSocket in project pinpoint by naver.

the class UdpSocketTest method testRemoteSend.

// @Test
public void testRemoteSend() throws IOException, InterruptedException {
    DatagramSocket so = new DatagramSocket();
    so.connect(new InetSocketAddress("10.66.18.78", PORT));
    so.send(newDatagramPacket(1500));
    so.send(newDatagramPacket(10000));
    so.send(newDatagramPacket(20000));
    so.send(newDatagramPacket(50000));
    so.send(newDatagramPacket(60000));
    so.send(newDatagramPacket(AcceptedSize));
    try {
        so.send(newDatagramPacket(AcceptedSize + 1));
        Assert.fail("failed");
    } catch (IOException ignore) {
    }
    try {
        so.send(newDatagramPacket(70000));
        Assert.fail("failed");
    } catch (IOException ignore) {
    }
    so.close();
}
Also used : DatagramSocket(java.net.DatagramSocket) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException)

Aggregations

DatagramSocket (java.net.DatagramSocket)294 DatagramPacket (java.net.DatagramPacket)137 IOException (java.io.IOException)112 SocketException (java.net.SocketException)74 InetAddress (java.net.InetAddress)63 InetSocketAddress (java.net.InetSocketAddress)46 UnknownHostException (java.net.UnknownHostException)33 Test (org.junit.Test)27 SocketTimeoutException (java.net.SocketTimeoutException)24 InterruptedIOException (java.io.InterruptedIOException)18 PortUnreachableException (java.net.PortUnreachableException)18 ServerSocket (java.net.ServerSocket)18 BindException (java.net.BindException)16 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)16 DatagramChannel (java.nio.channels.DatagramChannel)14 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 MulticastSocket (java.net.MulticastSocket)10 SocketAddress (java.net.SocketAddress)9 ByteBuffer (java.nio.ByteBuffer)8 ArrayList (java.util.ArrayList)6