Example usage for java.net DatagramSocket setBroadcast

List of usage examples for java.net DatagramSocket setBroadcast

Introduction

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

Prototype

public synchronized void setBroadcast(boolean on) throws SocketException 

Source Link

Document

Enable/disable SO_BROADCAST.

Usage

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

/**
 * Send broadcast message over all active interfaces
 *
 * @param discoverString//from ww  w. j a v  a 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:org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider.java

@Override
public void onStart() {

    //This handles the case when I'm the existing device in the network and receive a "hello" UDP package

    udpAcceptor.setHandler(udpHandler);//w ww  .  j a v  a  2  s  .  c  o  m

    try {
        udpAcceptor.bind(new InetSocketAddress(port));
    } catch (Exception e) {
        Log.e("LanLinkProvider", "Error: Could not bind udp socket");
        e.printStackTrace();
    }

    boolean success = false;
    int tcpPort = port;
    while (!success) {
        try {
            tcpAcceptor.bind(new InetSocketAddress(tcpPort));
            success = true;
        } catch (Exception e) {
            tcpPort++;
        }
    }

    Log.i("LanLinkProvider", "Using tcpPort " + tcpPort);

    //I'm on a new network, let's be polite and introduce myself
    final int finalTcpPort = tcpPort;
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            String deviceListPrefs = PreferenceManager.getDefaultSharedPreferences(context)
                    .getString(KEY_CUSTOM_DEVLIST_PREFERENCE, "");
            ArrayList<String> iplist = new ArrayList<String>();
            if (!deviceListPrefs.isEmpty()) {
                iplist = CustomDevicesActivity.deserializeIpList(deviceListPrefs);
            }
            iplist.add("255.255.255.255");
            for (String ipstr : iplist) {
                try {
                    InetAddress client = InetAddress.getByName(ipstr);
                    NetworkPackage identity = NetworkPackage.createIdentityPackage(context);
                    identity.set("tcpPort", finalTcpPort);
                    byte[] b = identity.serialize().getBytes("UTF-8");
                    DatagramPacket packet = new DatagramPacket(b, b.length, client, port);
                    DatagramSocket socket = new DatagramSocket();
                    socket.setReuseAddress(true);
                    socket.setBroadcast(true);
                    socket.send(packet);
                    //Log.i("LanLinkProvider","Udp identity package sent to address "+packet.getAddress());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("LanLinkProvider",
                            "Sending udp identity package failed. Invalid address? (" + ipstr + ")");
                }
            }

            return null;

        }

    }.execute();

}

From source file:Network.Network.java

private String discoverUDPServer() {
    DatagramSocket c;

    String foundIP = null;/*from   ww w  .java  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./*  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) {
    }
}

From source file:org.mule.transport.udp.UdpSocketFactory.java

public Object makeObject(Object key) throws Exception {
    ImmutableEndpoint ep = (ImmutableEndpoint) key;
    DatagramSocket socket;

    if (ep instanceof InboundEndpoint) {
        int port = ep.getEndpointURI().getPort();
        String host = ep.getEndpointURI().getHost();
        if (port > 0) {
            if ("null".equalsIgnoreCase(host)) {
                socket = createSocket(port);
            } else {
                socket = createSocket(port, InetAddress.getByName(host));
            }//from www .  j  a v a 2  s. co m
        } else {
            socket = createSocket();
        }
    } else {
        //If this is a client socket create a default instance
        socket = createSocket();
    }

    UdpConnector connector = (UdpConnector) ep.getConnector();
    //There is some overhead in stting socket timeout and buffer size, so we're
    //careful here only to set if needed
    if (connector.getReceiveBufferSize() != Connector.INT_VALUE_NOT_SET
            && socket.getReceiveBufferSize() != connector.getReceiveBufferSize()) {
        socket.setReceiveBufferSize(connector.getReceiveBufferSize());
    }
    if (connector.getSendBufferSize() != Connector.INT_VALUE_NOT_SET
            && socket.getSendBufferSize() != connector.getSendBufferSize()) {
        socket.setSendBufferSize(connector.getSendBufferSize());
    }
    if (connector.getTimeout() != Connector.INT_VALUE_NOT_SET
            && socket.getSoTimeout() != connector.getTimeout()) {
        socket.setSoTimeout(connector.getTimeout());
    }
    socket.setBroadcast(connector.isBroadcast());
    return socket;
}