Example usage for java.net DatagramSocket DatagramSocket

List of usage examples for java.net DatagramSocket DatagramSocket

Introduction

In this page you can find the example usage for java.net DatagramSocket DatagramSocket.

Prototype

public DatagramSocket() throws SocketException 

Source Link

Document

Constructs a datagram socket and binds it to any available port on the local host machine.

Usage

From source file:com.vuze.plugin.azVPN_PIA.Checker.java

private int handleUnboundOrLoopback(InetAddress bindIP, StringBuilder sReply) {

    int newStatusID = STATUS_ID_OK;

    InetAddress newBindIP = null;
    NetworkInterface newBindNetworkInterface = null;

    String s;/*w ww. j  a  va  2s.c  om*/

    if (bindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "pia.vuze.unbound");
    } else {
        addReply(sReply, CHAR_BAD, "pia.vuze.loopback");
    }

    try {
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();

        // Find a bindable address that starts with 10.
        InetAddress[] bindableAddresses = networkAdmin.getBindableAddresses();

        for (InetAddress bindableAddress : bindableAddresses) {
            if (matchesVPNIP(bindableAddress)) {
                newBindIP = bindableAddress;
                newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);

                addReply(sReply, CHAR_GOOD, "pia.found.bindable.vpn", new String[] { "" + newBindIP });

                break;
            }
        }

        // Find a Network Interface that has an address that starts with 10.
        NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces();

        boolean foundNIF = false;
        for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
            NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
            for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                InetAddress address = a.getAddress();
                if (address instanceof Inet4Address) {
                    if (matchesVPNIP(address)) {
                        s = texts.getLocalisedMessageText("pia.possible.vpn",
                                new String[] { "" + address, networkAdminInterface.getName() + " ("
                                        + networkAdminInterface.getDisplayName() + ")" });

                        if (newBindIP == null) {
                            foundNIF = true;
                            newBindIP = address;

                            // Either one should work
                            //newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);
                            newBindNetworkInterface = NetworkInterface
                                    .getByName(networkAdminInterface.getName());

                            s = CHAR_GOOD + " " + s + ". " + texts.getLocalisedMessageText("pia.assuming.vpn");
                        } else if (address.equals(newBindIP)) {
                            s = CHAR_GOOD + " " + s + ". " + texts.getLocalisedMessageText("pia.same.address");
                            foundNIF = true;
                        } else {
                            if (newStatusID != STATUS_ID_BAD) {
                                newStatusID = STATUS_ID_WARN;
                            }
                            s = CHAR_WARN + " " + s + ". "
                                    + texts.getLocalisedMessageText("pia.not.same.address");
                        }

                        addLiteralReply(sReply, s);

                        if (rebindNetworkInterface) {
                            // stops message below from being added, we'll rebind later
                            foundNIF = true;
                        }

                    }
                }
            }
        }

        if (!foundNIF) {
            addReply(sReply, CHAR_BAD, "pia.interface.not.found");
        }

        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows, but on Mac returns a wildcard address
        DatagramSocket socket = new DatagramSocket();
        socket.connect(testSocketAddress, 0);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();

        if (!localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("pia.nonvuze.probable.route",
                    new String[] { "" + localAddress, networkInterface == null ? "null"
                            : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) {

                if (newBindIP == null) {
                    newBindIP = localAddress;
                    newBindNetworkInterface = networkInterface;

                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("pia.assuming.vpn");
                } else if (localAddress.equals(newBindIP)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("pia.same.address");
                } else {
                    // Vuze not bound. We already found a boundable address, but it's not this one
                    /* Possibly good case:
                     * - Vuze: unbound
                     * - Found Bindable: 10.100.1.6
                     * - Default Routing: 10.255.1.1
                     * -> Split network
                     */
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s = CHAR_WARN + " " + s + " " + texts.getLocalisedMessageText("pia.not.same.future.address")
                            + " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting")
                            + " " + texts.getLocalisedMessageText(
                                    "default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);

            } else {
                s = CHAR_WARN + " " + s;
                if (!bindIP.isLoopbackAddress()) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }

                if (newBindIP == null && foundNIF) {
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s += " " + texts
                            .getLocalisedMessageText("default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "pia.nat.error", new String[] { e.toString() });
    }

    if (newBindIP == null) {
        addReply(sReply, CHAR_BAD, "pia.vpn.ip.detect.fail");
        return STATUS_ID_BAD;
    }

    rebindNetworkInterface(newBindNetworkInterface, newBindIP, sReply);
    return newStatusID;
}

From source file:com.vuze.plugin.azVPN_Air.Checker.java

private int handleBound(InetAddress bindIP, StringBuilder sReply) {
    int newStatusID = STATUS_ID_OK;

    String s;//from  w  w  w.  ja  va 2  s.  c o  m
    boolean isGoodExistingBind = matchesVPNIP(bindIP);
    if (isGoodExistingBind) {
        String niName = "Unknown Interface";
        try {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(bindIP);
            niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
        } catch (Throwable e) {
        }
        addReply(sReply, CHAR_GOOD, "airvpn.bound.good", new String[] { "" + bindIP, niName });
        vpnIP = bindIP;
    } else {
        addReply(sReply, CHAR_BAD, "airvpn.bound.bad", new String[] { "" + bindIP });
        newStatusID = STATUS_ID_BAD;
    }

    try {
        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows (in some cases), but on Mac returns a wildcard 
        // address
        DatagramSocket socket = new DatagramSocket();
        socket.connect(testSocketAddress, 0);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();

        if (!localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("airvpn.nonvuze.probable.route", new String[] { "" + localAddress,
                    networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });
            char replyChar = ' ';

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) {

                if (localAddress.equals(bindIP)) {
                    replyChar = isGoodExistingBind ? CHAR_GOOD : CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("airvpn.same.as.vuze");
                } else {
                    // Vuze is bound, default routing goes somewhere else
                    // This is ok, since Vuze will not accept incoming from "somewhere else"
                    // We'll warn, but not update the status id

                    replyChar = CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("airvpn.not.same");

                    if (isGoodExistingBind) {
                        s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                    }
                }

                addLiteralReply(sReply, replyChar + " " + s);

                if (!isGoodExistingBind && rebindNetworkInterface) {
                    rebindNetworkInterface(networkInterface, localAddress, sReply);
                    // Should we redo test?
                }

            } else {
                // Vuze is bound, default routing goes to somewhere else.
                // Probably network splitting
                replyChar = isGoodExistingBind ? CHAR_WARN : CHAR_BAD;
                if (isGoodExistingBind) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }
                addLiteralReply(sReply, replyChar + " " + s);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return newStatusID;
}

From source file:com.vuze.plugin.azVPN_Air.Checker.java

private int handleUnboundOrLoopback(InetAddress bindIP, StringBuilder sReply) {

    int newStatusID = STATUS_ID_OK;

    InetAddress newBindIP = null;
    NetworkInterface newBindNetworkInterface = null;

    String s;/*  w ww.j  av  a  2s  .com*/

    if (bindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "airvpn.vuze.unbound");
    } else {
        addReply(sReply, CHAR_BAD, "airvpn.vuze.loopback");
    }

    try {
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();

        // Find a bindable address that starts with 10.
        InetAddress[] bindableAddresses = networkAdmin.getBindableAddresses();

        for (InetAddress bindableAddress : bindableAddresses) {
            if (matchesVPNIP(bindableAddress)) {
                newBindIP = bindableAddress;
                newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);

                addReply(sReply, CHAR_GOOD, "airvpn.found.bindable.vpn", new String[] { "" + newBindIP });

                break;
            }
        }

        // Find a Network Interface that has an address that starts with 10.
        NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces();

        boolean foundNIF = false;
        for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
            NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
            for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                InetAddress address = a.getAddress();
                if (address instanceof Inet4Address) {
                    if (matchesVPNIP(address)) {
                        s = texts.getLocalisedMessageText("airvpn.possible.vpn",
                                new String[] { "" + address, networkAdminInterface.getName() + " ("
                                        + networkAdminInterface.getDisplayName() + ")" });

                        if (newBindIP == null) {
                            foundNIF = true;
                            newBindIP = address;

                            // Either one should work
                            //newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);
                            newBindNetworkInterface = NetworkInterface
                                    .getByName(networkAdminInterface.getName());

                            s = CHAR_GOOD + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.assuming.vpn");
                        } else if (address.equals(newBindIP)) {
                            s = CHAR_GOOD + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.same.address");
                            foundNIF = true;
                        } else {
                            if (newStatusID != STATUS_ID_BAD) {
                                newStatusID = STATUS_ID_WARN;
                            }
                            s = CHAR_WARN + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.not.same.address");
                        }

                        addLiteralReply(sReply, s);

                        if (rebindNetworkInterface) {
                            // stops message below from being added, we'll rebind later
                            foundNIF = true;
                        }

                    }
                }
            }
        }

        if (!foundNIF) {
            addReply(sReply, CHAR_BAD, "airvpn.interface.not.found");
        }

        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows, but on Mac returns a wildcard address
        DatagramSocket socket = new DatagramSocket();
        socket.connect(testSocketAddress, 0);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();

        if (!localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("airvpn.nonvuze.probable.route",
                    new String[] { "" + localAddress, networkInterface == null ? "null"
                            : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) {

                if (newBindIP == null) {
                    newBindIP = localAddress;
                    newBindNetworkInterface = networkInterface;

                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.assuming.vpn");
                } else if (localAddress.equals(newBindIP)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.same.address");
                } else {
                    // Vuze not bound. We already found a boundable address, but it's not this one
                    /* Possibly good case:
                     * - Vuze: unbound
                     * - Found Bindable: 10.100.1.6
                     * - Default Routing: 10.255.1.1
                     * -> Split network
                     */
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s = CHAR_WARN + " " + s + " "
                            + texts.getLocalisedMessageText("airvpn.not.same.future.address") + " "
                            + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting") + " "
                            + texts.getLocalisedMessageText(
                                    "default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);

            } else {
                s = CHAR_WARN + " " + s;
                if (!bindIP.isLoopbackAddress()) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }

                if (newBindIP == null && foundNIF) {
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s += " " + texts
                            .getLocalisedMessageText("default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "airvpn.nat.error", new String[] { e.toString() });
    }

    if (newBindIP == null) {
        addReply(sReply, CHAR_BAD, "airvpn.vpn.ip.detect.fail");
        return STATUS_ID_BAD;
    }

    rebindNetworkInterface(newBindNetworkInterface, newBindIP, sReply);
    return newStatusID;
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Sends a wake-on-lan packet for specified MAC address across subnet
 * /*  w  w  w  . j  a v a 2s.  com*/
 * @param macAddr
 *          the mac address to 'wake up'
 */
public static final void sendWakeOnLanPacket(String macAddr) {
    // Broadcast IP address
    final String IP = "255.255.255.255";
    final int port = 7;

    try {
        final byte[] MACBYTE = new byte[6];
        final String[] hex = macAddr.split("(\\:|\\-)");

        for (int i = 0; i < 6; i++) {
            MACBYTE[i] = (byte) Integer.parseInt(hex[i], 16);
        }
        final byte[] bytes = new byte[6 + 16 * MACBYTE.length];
        for (int i = 0; i < 6; i++) {
            bytes[i] = (byte) 0xff;
        }
        for (int i = 6; i < bytes.length; i += MACBYTE.length) {
            System.arraycopy(MACBYTE, 0, bytes, i, MACBYTE.length);
        }

        // Send UDP packet here
        final InetAddress address = InetAddress.getByName(IP);
        final DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
        final DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();

        LOGGER.info("Sent WOL packet to " + macAddr);
    } catch (final Exception e) {
        LOGGER.error("Error sending WOL packet to " + macAddr, e);
    }
}

From source file:serverTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/*from   www. jav a 2s  .com*/
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    //inBuffer = new byte[8192];
    //outBuffer = new byte[8192];
    inBuffer = new byte[65536];
    outBuffer = new byte[8192];

    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();
        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }

        JSONObject joAction = new JSONObject(action);
        JSONObject joCmd = new JSONObject();
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "NODE");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        // set timeout
        String actionName = joAction.get("name").toString();
        if (actionName.equals("add")) {
            socket.setSoTimeout(90000);
        } else if (actionName.equals("connect")) {
            socket.setSoTimeout(60000);
        } else {
            socket.setSoTimeout(60000);
        }
        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);
        receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);

        try {
            // send the data
            socket.send(packet2Send);
            // receive reply            
            socket.receive(receivedPacket);
            // the server reply is...
            result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            session.setAttribute("LastActive", System.currentTimeMillis());
        } catch (Exception excep) {
            String msg = excep.getMessage();
            //String msg = excep.toString();
            joCmd.remove("action");
            joAction.put("result", "Error:" + msg);
            joCmd.put("action", joAction);
            result = joCmd.toString();
        }
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}

From source file:vmTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;//from  w w w.j a va 2  s. com
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    inBuffer = new byte[65536];
    outBuffer = new byte[8192];
    /*
    if (this.user == null) {
    this.user = "admin";
    }*/

    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();

        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }

        JSONObject joCmd = new JSONObject();
        JSONObject joAction = new JSONObject(action);
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "VM");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        String actionName = joAction.get("name").toString();
        /*if (actionName.equals("migrate")) {
        socket.setSoTimeout(600000);
        } else {
        socket.setSoTimeout(60000);
        }*/
        socket.setSoTimeout(60000);

        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);

        try {
            // send the data
            socket.send(packet2Send);
            receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
            socket.receive(receivedPacket);
            // the server response is...
            result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            session.setAttribute("LastActive", System.currentTimeMillis());
        } catch (Exception excep) {
            String msg = excep.getMessage();
            //String msg = excep.toString();
            joCmd.remove("action");
            joAction.put("result", "Error:" + msg);
            joCmd.put("action", joAction);
            result = joCmd.toString();
        }
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}

From source file:com.mobiperf.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * //  w ww.  j a  va2  s.c o  m
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;
    long dataConsumedThisTask = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    // number * (packet sent + packet received)
    dataConsumedThisTask += num * (size + packetSize);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    incrementData(dataConsumedThisTask);
    return retval;
}

From source file:com.mobiperf.measurements.RRCTask.java

/** 
 * Send a single packet of the size indicated and wait for a response.
 * /*  w w w.  j  av a2s. co m*/
 * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the
 * time from when the packet was sent to when a response was returned by the echo server.
 * 
 * @param serverAddr Echo server to calculate round trip
 * @param size size of packet to send in bytes
 * @param rcvSize size of packets sent from the echo server
 * @param port where the echo server is listening
 * @return The round trip time for the packet
 * @throws IOException
 */
public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException {
    long startTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[rcvSize];
    long dataConsumedThisTask = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);

    dataConsumedThisTask += (size + rcvSize);

    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");

        socket.send(packet);
        socket.receive(packetRcv);
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out, trying again");
        socket.close();
        return -1;
    }
    long endTime = System.currentTimeMillis();
    Logger.d("Sending complete: " + endTime);
    incrementData(dataConsumedThisTask);
    return endTime - startTime;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * /* ww  w . j  a  v  a 2  s .  c o m*/
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    return retval;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Send a single packet of the size indicated and wait for a response.
 * /*  w  ww . j  a va2 s.co  m*/
 * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the
 * time from when the packet was sent to when a response was returned by the echo server.
 * 
 * @param serverAddr Echo server to calculate round trip
 * @param size size of packet to send in bytes
 * @param rcvSize size of packets sent from the echo server
 * @param port where the echo server is listening
 * @return The round trip time for the packet
 * @throws IOException
 */
public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException {
    long startTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[rcvSize];

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);

    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");

        socket.send(packet);
        socket.receive(packetRcv);
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out, trying again");
        socket.close();
        return -1;
    }
    long endTime = System.currentTimeMillis();
    Logger.d("Sending complete: " + endTime);

    return endTime - startTime;
}