Example usage for java.net MulticastSocket receive

List of usage examples for java.net MulticastSocket receive

Introduction

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

Prototype

public synchronized void receive(DatagramPacket p) throws IOException 

Source Link

Document

Receives a datagram packet from this socket.

Usage

From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java

/**
 * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called.
 * @param listener listener to notify of events
 * @throws IOException if socket error occurs
 * @throws NullPointerException if any argument is {@code null}
 *///from   www. ja  v  a  2  s  .  c o  m
public void start(NatPmpEventListener listener) throws IOException {
    Validate.notNull(listener);

    MulticastSocket socket = null;
    try {
        final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD
        final int port = 5350;
        final InetSocketAddress groupAddress = new InetSocketAddress(group, port);

        socket = new MulticastSocket(port);

        if (!currentSocket.compareAndSet(null, socket)) {
            IOUtils.closeQuietly(socket);
            return;
        }

        socket.setReuseAddress(true);

        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
                InetAddress addr = addrs.nextElement();

                try {
                    if (addr instanceof Inet4Address) {
                        socket.joinGroup(groupAddress, networkInterface);
                    }
                } catch (IOException ioe) { // NOPMD
                    // occurs with certain interfaces
                    // do nothing
                }
            }
        }

        ByteBuffer buffer = ByteBuffer.allocate(12);
        DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity());

        while (true) {
            buffer.clear();
            socket.receive(data);
            buffer.position(data.getLength());
            buffer.flip();

            if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore
                continue;
            }

            if (buffer.remaining() != 12) { // data isn't the expected size, ignore
                continue;
            }

            int version = buffer.get(0);
            if (version != 0) { // data doesn't have the correct version, ignore
                continue;
            }

            int opcode = buffer.get(1) & 0xFF;
            if (opcode != 128) { // data doesn't have the correct op, ignore
                continue;
            }

            int resultCode = buffer.getShort(2) & 0xFFFF;
            switch (resultCode) {
            case 0:
                break;
            default:
                continue; // data doesn't have a successful result, ignore
            }

            listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer));
        }

    } catch (IOException ioe) {
        if (currentSocket.get() == null) {
            return; // ioexception caused by interruption/stop, so just return without propogating error up
        }

        throw ioe;
    } finally {
        IOUtils.closeQuietly(socket);
        currentSocket.set(null);
    }
}

From source file:de.jaetzold.networking.SimpleServiceDiscovery.java

/**
 * Send a SSDP search message with the given search target (ST) and return a list of received responses.
 *//*w w w .  j av  a  2  s . c o  m*/
public Map<String, URL> discover(String searchTarget) {
    Log.d("HUE", "ServiceDiscovery.discover");
    final InetSocketAddress address;
    // standard multicast port for SSDP
    try {
        // multicast address with administrative scope
        address = new InetSocketAddress(InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
        //address = InetAddress.getByName(MULTICAST_ADDRESS);

    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not get multicast address", e);
    }

    final MulticastSocket socket;
    try {
        socket = new MulticastSocket(null);

        InetAddress localhost = getAndroidLocalIP();

        InetSocketAddress srcAddress = new InetSocketAddress(localhost, MULTICAST_PORT);
        Log.d("HUE", "" + srcAddress.getAddress());
        socket.bind(srcAddress);
        Log.d("HUE", "step 1");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not create multicast socket");
    }

    try {
        socket.setSoTimeout(socketTimeout);
        Log.d("HUE", "step 2");
    } catch (SocketException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set socket timeout", e);
    }

    try {
        socket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
        Log.d("HUE", "step 3");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not make multicast socket joinGroup " + address, e);
    }
    try {
        socket.setTimeToLive(ttl);
        Log.d("HUE", "step 4");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set TTL " + ttl, e);
    }
    final byte[] transmitBuffer;
    try {
        transmitBuffer = constructSearchMessage(searchTarget).getBytes(CHARSET_NAME);
        Log.d("HUE", "step 5");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new IllegalStateException("WTF? " + CHARSET_NAME + " is not supported?", e);
    }
    DatagramPacket packet = null;
    try {
        packet = new DatagramPacket(transmitBuffer, transmitBuffer.length, address);
        Log.d("HUE", "step 6");
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        socket.send(packet);
        Log.d("HUE", "step 7");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not send search request", e);
    }
    Map<String, URL> result = new HashMap<String, URL>();
    byte[] receiveBuffer = new byte[1536];
    while (true) {
        try {
            Log.d("HUE", "sending packets");
            final DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length,
                    InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
            socket.receive(receivePacket);
            //Log.d("HUE", new String(receivePacket.getData()));
            HueBridge response = parseResponsePacket(receivePacket);
            if (response != null) {
                Log.d("HUE", "resonse not null");
                ////System.out.println("resonse not null");
                result.put(response.getUDN(), response.getBaseUrl());
            } else {
                Log.d("HUE", "no bridge");
            }
        } catch (SocketTimeoutException e) {
            Log.e("HUE", "timeout exception");
            break;
        } catch (IOException e) {
            throw new IllegalStateException("Problem receiving search responses", e);
        }
    }
    return result;
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Starts Multicast Discovery Service. This can only
 * be invoked by a Nebula ClusterManager.
 * /*www  . j  av a  2 s  . co m*/
 * @throws IOException if occurred during operation
 * @throws UnsupportedOperationException if invoked by non-ClusterManager nodes.
 */
public static void startService() throws IOException, UnsupportedOperationException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    // Start Service
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {

                // Start Multicast Socket and listen for Requests
                final MulticastSocket mSock = new MulticastSocket(SERVICE_PORT);
                mSock.joinGroup(SERVICE_REQUEST_IP);

                // Infinite Loop
                while (true) {
                    // Buffer (for Greeting Message)
                    byte[] msg = new byte[GREET_MSG.getBytes("UTF-8").length];

                    // Create Datagram Packet
                    DatagramPacket packet = new DatagramPacket(msg, msg.length);

                    // Wait and Receive Request
                    mSock.receive(packet);
                    log.debug("[MulticastDiscovery] Received Discovery Request");

                    // Check if Greeting Message is valid
                    try {
                        String greet = new String(packet.getData());
                        if (!greet.equals(GREET_MSG)) {
                            throw new IllegalArgumentException("Invalid Greeting");
                        }
                    } catch (Exception e) {
                        log.debug("Malformed Multicast Message Igonored");
                        continue;
                    }

                    // Respond
                    doRespond();
                }

            } catch (IOException e) {
                log.error("[MulticastDiscovery] Service Failed on Receive", e);
            }

        }

    });
    t.setDaemon(true); // Run as Daemon thread
    t.start(); // Start Service
    log.debug("[MulticastDiscovery] Service Started");
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Discovery Process to identify Clusters with in 
 * network./*from  w  w w. j  a v a2  s.co m*/
 * 
 * @throws IOException if occurred during operation
 */
private void doDiscover() throws IOException {

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Wait for Response
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Receive
    resSock.setSoTimeout((int) TIMEOUT);
    try {
        resSock.receive(response);
    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    }

    byte[] data = response.getData();

    byte[] ipBytes = Arrays.copyOfRange(data, 0, 4);
    byte[] portBytes = Arrays.copyOfRange(data, 4, 9);

    InetAddress ip = InetAddress.getByAddress(ipBytes);
    StringBuilder sb = new StringBuilder(ip.getHostAddress());
    sb.append(":");
    for (byte b : portBytes) {
        sb.append(b);
    }

    this.cluster = sb.toString();
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Attempts to discover peer clusters using Multicast
 * Discovery. Each discovered Cluster will be notified
 * to the {@code PeerClusterService} of the 
 * ClusterManager./*  www. jav a  2  s  .  c  o m*/
 * 
 * @throws IOException if occurred during process
 */
public static void discoverPeerClusters() throws IOException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    log.info("[MulticastDiscovery] Discovering Peer Clusters...");

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Response Socket
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Set Socket Timeout
    resSock.setSoTimeout((int) TIMEOUT);

    try {

        // Loop until Socket Timeout Occurs
        while (true) {

            // Receive
            resSock.receive(response);
            processPeerResponse(response.getData());

        }

    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    } finally {
        log.info("[MulticastDiscovery] Peer Cluster Discovery Complete");
    }

}

From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java

/**
 * Scans all messages that arrive on the socket and scans them for the
 * search keywords. The search is not case sensitive.
 * /*  w  w w .  ja  v  a 2 s.  com*/
 * @param socket
 *            The socket where the answers arrive.
 * @param keywords
 *            The keywords to be searched for.
 * @return
 * @throws IOException
 */
private String scanResposesForKeywords(MulticastSocket socket, String... keywords) throws IOException {
    // In the worst case a SocketTimeoutException raises
    socket.setSoTimeout(2000);
    do {
        logger.debug("Got an answer message.");
        byte[] rxbuf = new byte[8192];
        DatagramPacket packet = new DatagramPacket(rxbuf, rxbuf.length);
        socket.receive(packet);
        String foundIp = analyzePacket(packet, keywords);
        if (foundIp != null) {
            return foundIp;
        }
    } while (true);
}

From source file:org.openhab.binding.wemo.internal.WemoBinding.java

public void wemoDiscovery() {
    logger.debug("wemoDiscovery() is called!");
    try {//  ww w.ja v a 2s .  c o m
        final int SSDP_PORT = 1900;
        final int SSDP_SEARCH_PORT = 1901;

        // Broadcast address
        final String SSDP_IP = "239.255.255.250";

        // Connection timeout
        int TIMEOUT = 1000;

        // Send from localhost:1901
        InetAddress localhost = InetAddress.getLocalHost();
        InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);

        // Send to 239.255.255.250:1900
        InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT);

        // Request-Packet-Constructor
        StringBuffer discoveryMessage = new StringBuffer();
        discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n");
        discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n");
        discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
        discoveryMessage.append("MX: 5\r\n");
        discoveryMessage.append("ST: urn:Belkin:service:basicevent:1\r\n");
        discoveryMessage.append("\r\n");
        logger.trace("Request: {}", discoveryMessage.toString());
        byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes();
        DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length,
                dstAddress);

        // Send multi-cast packet
        MulticastSocket multicast = null;
        try {
            multicast = new MulticastSocket(null);
            multicast.bind(srcAddress);
            logger.trace("Source-Address = '{}'", srcAddress);
            multicast.setTimeToLive(5);
            logger.trace("Send multicast request.");
            multicast.send(discoveryPacket);
        } finally {
            logger.trace("Multicast ends. Close connection.");
            multicast.disconnect();
            multicast.close();
        }

        // Response-Listener
        MulticastSocket wemoReceiveSocket = null;
        DatagramPacket receivePacket = null;
        try {
            wemoReceiveSocket = new MulticastSocket(SSDP_SEARCH_PORT);
            wemoReceiveSocket.setTimeToLive(10);
            wemoReceiveSocket.setSoTimeout(TIMEOUT);
            logger.debug("Send datagram packet.");
            wemoReceiveSocket.send(discoveryPacket);

            while (true) {
                try {
                    logger.debug("Receive SSDP Message.");
                    receivePacket = new DatagramPacket(new byte[2048], 2048);
                    wemoReceiveSocket.receive(receivePacket);
                    final String message = new String(receivePacket.getData());
                    if (message.contains("Belkin")) {
                        logger.trace("Received message: {}", message);
                    }

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (message != null) {
                                String location = StringUtils.substringBetween(message, "LOCATION: ",
                                        "/setup.xml");
                                String udn = StringUtils.substringBetween(message, "USN: uuid:",
                                        "::urn:Belkin");
                                if (udn != null) {
                                    logger.trace("Save location '{}' for WeMo device with UDN '{}'", location,
                                            udn);
                                    wemoConfigMap.put(udn, location);
                                    logger.info("Wemo Device with UDN '{}' discovered", udn);
                                }
                            }
                        }
                    }).start();

                } catch (SocketTimeoutException e) {
                    logger.debug("Message receive timed out.");
                    for (String name : wemoConfigMap.keySet()) {
                        logger.trace(name + ":" + wemoConfigMap.get(name));
                    }
                    break;
                }
            }
        } finally {
            if (wemoReceiveSocket != null) {
                wemoReceiveSocket.disconnect();
                wemoReceiveSocket.close();
            }
        }

    } catch (Exception e) {
        logger.error("Could not start wemo device discovery", e);
    }

}

From source file:org.openhab.binding.yeelight.internal.YeelightBinding.java

private void receiveData(MulticastSocket socket, DatagramPacket dgram) {

    try {// w w w  .  j  a  v a2s .  c o m
        while (true) {
            socket.receive(dgram);
            String sentence = new String(dgram.getData(), 0, dgram.getLength());

            logger.debug("Yeelight received packet: {}", sentence);

            if (isOKPacket(sentence) || isNotifyPacket(sentence)) {
                String[] lines = sentence.split("\n");
                String id = "";
                String location = "";
                String model = "";
                String support = "";
                for (String line : lines) {
                    line = line.replace("\r", "");
                    line = line.replace("\n", "");

                    if (line.startsWith("id: "))
                        id = line.substring(4);
                    else if (line.startsWith("Location: "))
                        location = line.substring(10);
                    else if (line.startsWith("model: "))
                        model = line.substring(7);
                    else if (line.startsWith("support: "))
                        support = line.substring(9);
                }
                if (!id.equals("") && !devices.containsKey(id)) {
                    YeelightDevice device = new YeelightDevice(id, location, model, support);
                    devices.put(id, device);
                    logger.info("Found Yeelight device :\n{}", device.toString());
                }
            }
        }
    } catch (IOException e) {
        logger.error(e.toString());
    }
}

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {/* w  w w. j  av  a2  s.c  om*/
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticast() throws Exception {
    MulticastSocket socket;/*from  w  ww.  j  ava 2 s. co m*/
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final String multicastAddress = this.multicastRule.getGroup();
    final String payload = "foo";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch received = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[8];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[length];
            System.arraycopy(src, offset, dest, 0, length);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            received.countDown();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.afterPropertiesSet();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(received.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}