Example usage for java.net DatagramSocket close

List of usage examples for java.net DatagramSocket close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes this datagram socket.

Usage

From source file:org.cc86.MMC.client.Main.java

public static String serverDiscovery() {
    String res = "0.0.0.0";
    DatagramSocket c;
    // Find the server using UDP broadcast
    try {//from  w  ww.j  a va  2  s. co  m
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 0xCC86);
            c.send(sendPacket);
            l.info("Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }

                l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: "
                        + networkInterface.getDisplayName());
            }
        }

        l.info("Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_MMC_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            res = (receivePacket.getAddress() + "").substring(1);
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {

    }
    return res;
}

From source file:gravity.android.discovery.DiscoveryServer.java

public void run() {
    Log.v("DISCOVERY_SERVER", "SERVER STARTED");

    DatagramSocket serverSocket = null;

    try {//w  ww.  j  ava2  s  .c  om
        serverSocket = new DatagramSocket(port);
        byte[] receiveData;
        byte[] sendData;

        while (this.isInterrupted() == false) {
            receiveData = new byte[128];
            sendData = new byte[128];

            try {
                Log.v("DISCOVERY_SERVER", "LISTENING");
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());

                if (sentence != null)
                    Log.v("DISCOVERY_SERVER",
                            "RECEIVED: " + sentence.substring(0, receivePacket.getLength()).trim());

                if (sentence != null && sentence.substring(0, receivePacket.getLength()).trim().equals(token)) {
                    Log.v("DISCOVERY_SERVER", "SEND '" + nome + "' to "
                            + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort());
                    JSONObject sendDataJson = new JSONObject();
                    sendDataJson.accumulate("name", nome);
                    sendDataJson.accumulate("port_to_share", port_to_share);

                    //sendData = (nome + "," + port_to_share).getBytes();
                    sendData = sendDataJson.toString().getBytes(); //Prakash: converts the data to json objects to avoid troubles

                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                            receivePacket.getAddress(), receivePacket.getPort());
                    serverSocket.send(sendPacket);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e("DISCOVERY_SERVER", ex.toString());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("DISCOVERY_SERVER", e.toString());
    } finally {
        try {
            if (serverSocket != null)
                serverSocket.close();
        } catch (Exception ex) {
        }
    }

}

From source file:org.opendaylight.lispflowmapping.integrationtest.MappingServiceIntegrationTest.java

License:asdf

private void sendProxyMapRequest(String rloc, int port, LispAFIAddress adLcaf)
        throws SocketTimeoutException, SocketException {
    String eid = "10.1.0.1";
    MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
    sendMapRequest(mapRequest);//from  w  ww  .  ja  va  2s  . com
    DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
    MapRequest recievedMapRequest = receiveMapRequest(nonProxySocket);
    assertEquals(mapRequest.getNonce(), recievedMapRequest.getNonce());
    assertEquals(mapRequest.getSourceEid(), recievedMapRequest.getSourceEid());
    assertEquals(mapRequest.getItrRloc(), recievedMapRequest.getItrRloc());
    assertEquals(mapRequest.getEidRecord(), recievedMapRequest.getEidRecord());
    nonProxySocket.close();
}

From source file:snapshotTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/* w  w w  .  j  a v  a2  s.  c  o  m*/
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    inBuffer = new byte[8192];
    outBuffer = new byte[8192];
    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", "SNAPSHOT");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        String actionName = joAction.get("name").toString();
        if (actionName.equals("create")) {
            socket.setSoTimeout(180000);
        } else {
            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:gravity.android.discovery.DiscoveryClient.java

public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) {
    ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>();

    try {/*from   w  w w  . j  ava  2  s  .  c o m*/
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.setBroadcast(true);
        InetAddress IPAddress = Utils.getBroadcastAddress(mWifi);
        Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress());
        byte[] receiveData = new byte[2048];
        byte[] sendData = new byte[128];

        sendData = token.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        Log.v("DISCOVERY_CLIENT", "sent " + token);
        clientSocket.send(sendPacket);

        long t1 = System.currentTimeMillis();
        while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            try {
                clientSocket.setSoTimeout(500);
                clientSocket.receive(receivePacket);

                if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) {
                    String discovered_name, discovered_ip;
                    int discovered_port;

                    String received = new String(receivePacket.getData());

                    if (received != null) {
                        received = received.trim().substring(0, receivePacket.getLength()).trim();
                        Log.d("Recieved Msg Packet:", received);

                        //StringTokenizer st = new StringTokenizer(received, ",");

                        //Gravity Code
                        JSONObject recievedJson = new JSONObject(received);

                        try {
                            //discovered_name = st.nextToken();   
                            discovered_name = recievedJson.getString("name"); //Gravity code

                            discovered_ip = receivePacket.getAddress().getHostAddress();

                            //discovered_port = Integer.parseInt(st.nextToken());
                            discovered_port = recievedJson.getInt("port_to_share"); //Gravity code

                            Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip
                                    + ":" + discovered_port);

                            boolean add = true;
                            if (ret.size() > 0) {
                                for (DiscoveryServerInfo dsi : ret) {
                                    if (dsi != null && dsi.ip.equals(discovered_ip)) {
                                        add = false;
                                        break;
                                    }
                                }
                            }

                            if (add) {
                                ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip,
                                        discovered_port));
                            }
                        } catch (NoSuchElementException nsee) {
                            Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage());
                        }

                    }
                }

            } catch (SocketTimeoutException tex) {
                /* ignored */ }
        }

        clientSocket.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.e("DISCOVERY_CLIENT", ex.toString());
    }

    return ret;
}

From source file:vmXmlFile.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;//ww  w .  j a v  a 2  s .c o m
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    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 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();
        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);
        // 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());
        socket.close();

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

From source file:org.openhab.binding.harmonyhub.discovery.HarmonyHubDiscovery.java

/**
 * Send broadcast message over all active interfaces
 *
 * @param discoverString//from  w w w  .  ja va 2s.  c  o m
 *            String to be used for the discovery
 */
private void sendDiscoveryMessage(String discoverString) {
    DatagramSocket bcSend = null;
    try {
        bcSend = new DatagramSocket();
        bcSend.setBroadcast(true);

        byte[] sendData = discoverString.getBytes();

        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress[] broadcast = null;

                if (StringUtils.isNotBlank(optionalHost)) {
                    try {
                        broadcast = new InetAddress[] { InetAddress.getByName(optionalHost) };
                    } catch (Exception e) {
                        logger.error("Could not use host for hub discovery", e);
                        return;
                    }
                } else {
                    broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"),
                            InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() };
                }

                for (InetAddress bc : broadcast) {
                    // Send the broadcast package!
                    if (bc != null) {
                        try {
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc,
                                    DISCO_PORT);
                            bcSend.send(sendPacket);
                        } catch (IOException e) {
                            logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
                        } catch (Exception e) {
                            logger.debug(e.getMessage(), e);
                        }
                        logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(),
                                networkInterface.getDisplayName());
                    }
                }
            }
        }

    } catch (IOException e) {
        logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
    } finally {
        try {
            if (bcSend != null) {
                bcSend.close();
            }
        } catch (Exception e) {
            // Ignore
        }
    }

}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Attempts to retrieve the job managers address in the network through an
 * IP broadcast. This method should be called by the task manager.
 * /*  w w w  . j a  v a2s.c o  m*/
 * @return the socket address of the job manager in the network
 * @throws DiscoveryException
 *         thrown if the job manager's socket address could not be
 *         discovered
 */
public static InetSocketAddress getJobManagerAddress() throws DiscoveryException {

    final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER);
    final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT);

    InetSocketAddress jobManagerAddress = null;
    DatagramSocket socket = null;

    try {

        final Set<InetAddress> targetAddresses = getBroadcastAddresses();

        if (targetAddresses.isEmpty()) {
            throw new DiscoveryException("Could not find any broadcast addresses available to this host");
        }

        socket = new DatagramSocket();

        LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT);
        socket.setSoTimeout(CLIENTSOCKETTIMEOUT);

        final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE],
                RESPONSE_PACKET_SIZE);

        for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) {

            final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber);

            for (InetAddress broadcast : targetAddresses) {
                lookupRequest.setAddress(broadcast);
                lookupRequest.setPort(discoveryPort);
                LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress());
                socket.send(lookupRequest);
            }

            try {
                socket.receive(responsePacket);
            } catch (SocketTimeoutException ste) {
                LOG.debug("Timeout wainting for discovery reply. Retrying...");
                continue;
            }

            if (!isPacketForUs(responsePacket, magicNumber)) {
                LOG.debug("Received packet which is not destined to this Nephele setup");
                continue;
            }

            final int packetTypeID = getPacketTypeID(responsePacket);
            if (packetTypeID != JM_LOOKUP_REPLY_ID) {
                LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... ");
                continue;
            }

            final int ipcPort = extractIpcPort(responsePacket);

            // Replace port from discovery service with the actual RPC port
            // of the job manager
            if (USE_IPV6) {
                // TODO: No connection possible unless we remove the scope identifier
                if (responsePacket.getAddress() instanceof Inet6Address) {
                    try {
                        jobManagerAddress = new InetSocketAddress(
                                InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort);
                    } catch (UnknownHostException e) {
                        throw new DiscoveryException(StringUtils.stringifyException(e));
                    }
                } else {
                    throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address");
                }
            } else {
                jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort);
            }
            LOG.debug("Discovered job manager at " + jobManagerAddress);
            break;
        }

    } catch (IOException ioe) {
        throw new DiscoveryException(ioe.toString());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    if (jobManagerAddress == null) {
        LOG.debug("Unable to discover Jobmanager via IP broadcast");
        throw new DiscoveryException("Unable to discover JobManager via IP broadcast!");
    }

    return jobManagerAddress;
}

From source file:Network.Network.java

private String discoverUDPServer() {
    DatagramSocket c;

    String foundIP = null;//from ww w . j  av a 2  s  .  c om
    // Find the server using UDP broadcast
    try {
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_BATTLESHIPSERVER_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 8888);
            c.send(sendPacket);
            System.out.println(getClass().getName() + ">>> Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        /*// Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
                
        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
            continue; // Don't want to broadcast to the loopback interface
        }
                
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
            InetAddress broadcast = interfaceAddress.getBroadcast();
            if (broadcast == null) {
                continue;
            }
                
            // Send the broadcast package!
            try {
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                c.send(sendPacket);
            } 
            catch (Exception e) {
            }
                
            System.out.println(getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
        }
        }*/

        System.out.println(getClass().getName()
                + ">>> Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        System.out.println(getClass().getName() + ">>> Broadcast response from server: "
                + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_BATTLESHIPSERVER_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            foundIP = receivePacket.getAddress().getHostAddress();
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {
        Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
    }
    return foundIP;
}

From source file:net.fenyo.gnetwatch.actions.ActionFlood.java

/**
 * Floods the target.//from   w  w w  . ja v a 2 s.c o m
 * @param none.
 * @return void.
 * @throws IOException IO exception.
 * @throws InterruptedException exception.
 */
public void invoke() throws IOException, InterruptedException {
    if (isDisposed() == true)
        return;

    try {
        super.invoke();

        // il faudrait copier les queriers  la cration de l'action
        final IPQuerier querier;

        DatagramSocket socket;
        final byte[] buf;
        final DatagramPacket packet;
        // on invoque un champ persistent depuis potentiellement un thread autre que celui qu gre une session qui rend cet objet persistent, on doit viter cet accs concurrent (les sessions ne sont pas thread safe)
        synchronized (getGUI().getSynchro()) {
            if (TargetIPv4.class.isInstance(getTarget())) {
                querier = ((TargetIPv4) getTarget()).getIPQuerier();
            } else if (TargetIPv6.class.isInstance(getTarget())) {
                querier = ((TargetIPv6) getTarget()).getIPQuerier();
            } else
                return;

            socket = new DatagramSocket(querier.getPortSrc());
            socket.setTrafficClass(querier.getTos() << 2);
            socket.setBroadcast(true);

            buf = new byte[querier.getPDUMaxSize()];
            Arrays.fill(buf, (byte) 0);
            packet = new DatagramPacket(buf, buf.length,
                    new InetSocketAddress(querier.getAddress(), querier.getPortDst()));
        }

        long last_time = System.currentTimeMillis();
        int bytes_sent = 0;
        while (true) {
            socket.send(packet);
            bytes_sent += buf.length;

            if (System.currentTimeMillis() - last_time > 1000) {

                synchronized (getGUI().getSynchro()) {
                    synchronized (getGUI().sync_tree) {
                        final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            session.update(this);

                            getTarget().addEvent(new EventFlood(new Double(
                                    ((double) 8 * 1000 * bytes_sent) / (System.currentTimeMillis() - last_time))
                                            .intValue()));

                            setDescription(
                                    GenericTools.formatNumericString(getGUI().getConfig(),
                                            "" + new Double(((double) 8 * 1000 * bytes_sent)
                                                    / (System.currentTimeMillis() - last_time)).intValue())
                                            + " bit/s");

                            session.getTransaction().commit();
                        } catch (final Exception ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        }
                    }
                }

                synchronized (getGUI().getSynchro()) {
                    getGUI().setStatus(getGUI().getConfig().getPattern("bytes_flooded", bytes_sent,
                            querier.getAddress().toString().substring(1)));
                }

                last_time = System.currentTimeMillis();
                bytes_sent = 0;
            }

            if (interrupted == true) {
                socket.close();
                return;
            }
        }
    } catch (final InterruptedException ex) {
    }
}