Example usage for java.net DatagramPacket getData

List of usage examples for java.net DatagramPacket getData

Introduction

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

Prototype

public synchronized byte[] getData() 

Source Link

Document

Returns the data buffer.

Usage

From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {//from   w  ww  . j a v a2 s  .  co  m

        InetAddress localhost = InetAddress.getLocalHost();
        InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);

        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("ST: upnp:rootdevice\r\n");
        discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
        discoveryMessage.append("MX: 5\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(4);
            logger.debug("Send multicast request.");
            multicast.send(discoveryPacket);
        } finally {
            logger.trace("Multicast ends. Close connection.");
            multicast.disconnect();
            multicast.close();
        }

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

            while (true) {
                try {
                    receivePacket = new DatagramPacket(new byte[1536], 1536);
                    wemoReceiveSocket.receive(receivePacket);
                    final String message = new String(receivePacket.getData());
                    logger.trace("Received message: {}", message);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String label = "WeMo Device";
                            String wemoUDN = null;
                            String wemoLocation = null;
                            String wemoFriendlyName = null;
                            String wemoModelName = null;
                            ThingUID uid = null;

                            if (message != null) {
                                if (message.contains("Socket-1_0") || message.contains("Insight-1_0")
                                        || message.contains("Motion-1_0")
                                        || message.contains("Lightswitch-1_0")) {
                                    wemoUDN = StringUtils.substringBetween(message, "USN: uuid:",
                                            "::upnp:rootdevice");
                                    logger.debug("Wemo device with UDN '{}' found", wemoUDN);
                                    wemoLocation = StringUtils.substringBetween(message, "LOCATION: ",
                                            "/setup.xml");
                                    if (wemoLocation != null) {
                                        try {
                                            int timeout = 5000;
                                            String response = HttpUtil.executeUrl("GET",
                                                    wemoLocation + "/setup.xml", timeout);
                                            wemoFriendlyName = StringUtils.substringBetween(response,
                                                    "<friendlyName>", "</friendlyName>");
                                            logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName,
                                                    wemoLocation);
                                            wemoModelName = StringUtils.substringBetween(response,
                                                    "<modelName>", "</modelName>");
                                            logger.trace("Wemo device '{}' has model name '{}'",
                                                    wemoFriendlyName, wemoModelName);
                                            label = "Wemo" + wemoModelName;

                                            switch (wemoModelName) {
                                            case "Socket":
                                                logger.debug(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN);

                                                break;
                                            case "Insight":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN);
                                                break;
                                            case "LightSwitch":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN);
                                                break;
                                            case "Motion":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN);
                                                break;
                                            }
                                            Map<String, Object> properties = new HashMap<>(4);
                                            properties.put(UDN, wemoUDN);
                                            properties.put(LOCATION, wemoLocation);

                                            DiscoveryResult result = DiscoveryResultBuilder.create(uid)
                                                    .withProperties(properties).withLabel(label).build();
                                            thingDiscovered(result);

                                        } catch (Exception te) {
                                            logger.error("Could not discover WeMo device", te);
                                        }
                                    }
                                }
                            }
                        }
                    }).start();

                } catch (SocketTimeoutException e) {
                    logger.debug("Message receive timed out.");
                    break;
                }
            }
        } finally {
            if (wemoReceiveSocket != null) {
                wemoReceiveSocket.disconnect();
                wemoReceiveSocket.close();
            }
        }

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

}

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

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;/*from ww w  . j a v a  2 s.c  om*/
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[1000];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            socket1.setSoTimeout(8000);
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            assertTrue(ackListening.await(10, TimeUnit.SECONDS));
            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[6];
            System.arraycopy(src, offset + length - 6, dest, 0, 6);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
            mapper.setAcknowledge(true);
            mapper.setLengthCheck(true);
            Message<byte[]> message = mapper.toMessage(receivedPacket);
            Object id = message.getHeaders().get(IpHeaders.ACK_ID);
            byte[] ack = id.toString().getBytes();
            DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                    new InetSocketAddress(multicastRule.getNic(), ackPort.get()));
            DatagramSocket out = new DatagramSocket();
            out.send(ackPack);
            LogFactory.getLog(getClass())
                    .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress());
            out.close();
            ackSent.countDown();
            socket1.close();
        } 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,
            true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}

From source file:ru.novoscan.trkpd.snmp.spring.TrackSpringSnmpAgent.java

public void run() {
    try {//from  w w  w. j  av  a2  s.  c  o  m
        logger.debug("Binding to UDP port " + listeningPort);
        socket = new DatagramSocket(listeningPort);
    } catch (SocketException e) {
        // Fix: Flag to control lock socket within application
        isSocketException = true;
        throw new SnmpSystemException("Can not create SNMP agent UDP socket. Reason: " + e.getMessage());
    }

    // Fix: Flag to control lock socket within application
    isSocketCreated = true;

    while (!workerThread.isInterrupted()) {
        byte requestPacketBuffer[] = new byte[PACKET_MAX_SIZE];
        final DatagramPacket requestPacket = new DatagramPacket(requestPacketBuffer,
                requestPacketBuffer.length);
        try {
            socket.receive(requestPacket);
        } catch (IOException e) {
            logger.error("Error processing SNMP request. Reason: " + e.getMessage());
            continue;
        }
        final byte data[] = requestPacket.getData();
        Thread procThread = new Thread(new Runnable() {

            public void run() {
                try {
                    Message requestMsg;
                    Message responseMsg;
                    PDU requestPDU;
                    // Fix: Added missed ')' character
                    logger.debug("Received packet (length=" + data.length + " bytes)");
                    BerTlv tlv = new BerTlv();
                    tlv.decode(new ByteArrayInputStream(data));
                    requestMsg = new Message(tlv);
                    responseMsg = null;
                    requestPDU = (PDU) requestMsg.getPDU();
                    String requestedOID = requestPDU.getVarBindList().getVarBind(0).getObjectName()
                            .stringValue();

                    if (!hasHandledPrefix(requestedOID)) {

                        logger.info("No entry found for oid " + requestedOID);
                        GetResponsePDU responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 2, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                        return;
                    }

                    if (!validateCommunity(requestMsg)) {
                        logger.warn(
                                "Community [" + requestMsg.getComunity() + "] doesn't match for snmp request");
                        return;
                    }

                    GetResponsePDU responsePDU = null;
                    if (requestPDU instanceof GetRequestPDU)
                        responsePDU = handleGetRequest((GetRequestPDU) requestPDU);
                    else if (requestPDU instanceof GetNextRequestPDU)
                        responsePDU = handleGetNextRequest((GetNextRequestPDU) requestPDU);
                    else if (requestPDU instanceof SetRequestPDU)
                        responsePDU = handleSetRequest((SetRequestPDU) requestPDU);
                    else
                        responsePDU = createErrorResponse(requestPDU.getRequestId(), 5, 0,
                                requestPDU.getVarBindList());
                    responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                    logger.info("Sending response to client\n" + responseMsg.toString());
                    byte responsePacketBuffer[] = responseMsg.toBerTlv().getBytes();
                    if (responsePacketBuffer.length > PACKET_MAX_SIZE) {
                        responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 1, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(SNMP_VERSION, requestMsg.getComunity(), responsePDU);
                        responsePacketBuffer = responseMsg.toBerTlv().getBytes();
                    }
                    DatagramPacket responsePacket = new DatagramPacket(responsePacketBuffer,
                            responsePacketBuffer.length, requestPacket.getAddress(), requestPacket.getPort());
                    socket.send(responsePacket);
                } catch (Exception e) {
                    logger.error("Error processing SNMP request. Reason: " + e.getMessage());
                }
            }
        });
        procThread.start();
    }
}

From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java

public void startListener() {
    listeningExecutorService.submit(new Runnable() {

        private final int incomingBufferSize = 1024; //TODO check this

        @Override/*from   w  w w .jav a  2  s .c  o m*/
        public void run() {
            try {
                if (datagramSocket == null || datagramSocket.isClosed()) {
                    datagramSocket = new DatagramSocket(UDP_PORT, InetAddress.getByName("0.0.0.0"));
                    logger.info("opening upd socket {}", datagramSocket.getLocalSocketAddress());
                }
                final DatagramPacket datagramPacket = new DatagramPacket(new byte[incomingBufferSize],
                        incomingBufferSize);
                logger.trace("waiting for message on socket addr = {}", datagramSocket.getLocalSocketAddress());
                isListening = true;
                datagramSocket.receive(datagramPacket);
                processingExecutorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final String sourceAddress = datagramPacket.getAddress().getHostAddress();
                            ByteBuffer byteBuffer = ByteBuffer.wrap(datagramPacket.getData(),
                                    datagramPacket.getOffset(), datagramPacket.getLength());
                            int magic = byteBuffer.getInt(); //4 bytes
                            checkArgument(magic == MAGIC, "magic mismatch, expected %s, got %s", MAGIC, magic);
                            final LocalDiscoveryProtos.Announce announce = LocalDiscoveryProtos.Announce
                                    .parseFrom(ByteString.copyFrom(byteBuffer));
                            final String deviceId = hashDataToDeviceIdString(announce.getId().toByteArray());
                            if (!equal(deviceId, configuration.getDeviceId())) {
                                //                                logger.debug("received local announce from device id = {}", deviceId);
                                final List<DeviceAddress> deviceAddresses = Lists
                                        .newArrayList(Iterables.transform(
                                                firstNonNull(announce.getAddressesList(),
                                                        Collections.<String>emptyList()),
                                                new Function<String, DeviceAddress>() {
                                                    @Override
                                                    public DeviceAddress apply(String address) {
                                                        //                                /*
                                                        //                                When interpreting addresses with an unspecified address, e.g., tcp://0.0.0.0:22000 or tcp://:42424, the source address of the discovery announcement is to be used.
                                                        //                                 */
                                                        return DeviceAddress.newBuilder()
                                                                .setAddress(address.replaceFirst(
                                                                        "tcp://(0.0.0.0|):",
                                                                        "tcp://" + sourceAddress + ":"))
                                                                .setDeviceId(deviceId)
                                                                .setInstanceId(announce.getInstanceId())
                                                                .setProducer(
                                                                        DeviceAddress.AddressProducer.LOCAL_DISCOVERY)
                                                                .build();
                                                    }
                                                }));
                                boolean isNew = false;
                                synchronized (localDiscoveryRecords) {
                                    isNew = !localDiscoveryRecords.removeAll(deviceId).isEmpty();
                                    localDiscoveryRecords.putAll(deviceId, deviceAddresses);
                                }
                                eventBus.post(new MessageReceivedEvent() {
                                    @Override
                                    public List<DeviceAddress> getDeviceAddresses() {
                                        return Collections.unmodifiableList(deviceAddresses);
                                    }

                                    @Override
                                    public String getDeviceId() {
                                        return deviceId;
                                    }
                                });
                                if (isNew) {
                                    eventBus.post(new NewLocalPeerEvent() {
                                        @Override
                                        public String getDeviceId() {
                                            return deviceId;
                                        }
                                    });
                                }
                            }
                        } catch (Exception ex) {
                            logger.warn("error processing datagram", ex);
                        }
                    }
                });
                listeningExecutorService.submit(this);
            } catch (Exception ex) {
                isListening = false;
                if (listeningExecutorService.isShutdown()) {
                    return;
                }
                if (datagramSocket != null) {
                    logger.warn("error receiving datagram", ex);
                    listeningExecutorService.submit(this);
                } else if (ex instanceof java.net.BindException) {
                    logger.warn("error opening udp server socket : {}", ex.toString());
                } else {
                    logger.warn("error opening udp server socket", ex);
                }
            }
        }
    });
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

/**
 * WSIAdapter interface//from  ww w .java 2  s.com
 */

public List<Node> getAvailableNodeList() throws WSIAdapterException {

    logger.info("Getting available nodes...");

    nodesList = new ArrayList<Node>();

    List<String> wsnProxyList = new LinkedList<String>();
    wsnProxyList.add(Network.WLAB_OFFICE_PROXY_ADDRESS);
    wsnProxyList.add(Network.WLAB_LAB_PROXY_ADDRESS);

    DatagramSocket serverSocket = null;
    DatagramSocket clientSocket = null;
    String cmdString = "route";

    for (int i = 0; i < wsnProxyList.size(); i++) {
        try {
            serverSocket = new DatagramSocket(Constants.UDPSHELL_VGW_PORT);

            String hostProxyString = wsnProxyList.get(i);
            InetAddress hostProxy = InetAddress.getByName(hostProxyString);

            clientSocket = new DatagramSocket();
            byte[] bufCmd = new byte[10];
            bufCmd = cmdString.getBytes();
            DatagramPacket outcomingPacket = new DatagramPacket(bufCmd, bufCmd.length, hostProxy,
                    Constants.PROXY_UDPFORWARDER_PORT);
            clientSocket.send(outcomingPacket);

            boolean otherPackets = false;

            serverSocket.setSoTimeout(Constants.PROXY_RESPONSE_TIMEOUT);
            logger.info("Quering " + hostProxyString);
            try {
                byte[] bufAck = new byte[10];
                DatagramPacket ackPacket = new DatagramPacket(bufAck, bufAck.length);
                serverSocket.receive(ackPacket);
                String ackString = new String(ackPacket.getData()).trim();
                if (ackString.equals("ack")) {
                    otherPackets = true;
                }
            } catch (SocketTimeoutException e) {
                logger.warn(e.getMessage());
            }

            serverSocket.setSoTimeout(0);

            while (otherPackets) {
                try {
                    byte[] bufIncoming = new byte[1000];
                    DatagramPacket incomingPacket = new DatagramPacket(bufIncoming, bufIncoming.length);
                    serverSocket.receive(incomingPacket);
                    String currentNodeIP = new String(incomingPacket.getData()).trim();
                    if (!currentNodeIP.equals("end")) {
                        logger.info("Node: " + currentNodeIP);
                        nodesList.add(new Node(currentNodeIP));
                    } else {
                        otherPackets = false;
                        logger.info("No other nodes from " + hostProxyString);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

        } catch (UnknownHostException e) {
            logger.warn(e.getMessage() + " is not reachable.");
        } catch (SocketException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
            if (clientSocket != null) {
                clientSocket.close();
            }
        }
    }

    return nodesList;
}

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

@Test
public void verifySend() throws Exception {
    final int testPort = SocketUtils.findAvailableUdpSocket();
    byte[] buffer = new byte[8];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch = new CountDownLatch(1);
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                socket.receive(receivedPacket);
                latch.countDown();//from  w  w w  .ja v a  2s.c  o m
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    Thread.sleep(1000);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort);
    String payload = "foo";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch.await(3000, TimeUnit.MILLISECONDS));
    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));
    handler.shutDown();
}

From source file:org.rifidi.edge.adapter.csl.util.CslRfidTagServer.java

private boolean setMode(ReaderMode mode) {
    try {//ww w . ja  v a  2s.c  om

        InetAddress IPInet = InetAddress.getByName(this.IPAddress);

        // Set low-level API mode
        String cmd = "80" + byteArrayToHexString(IPInet.getAddress(), IPInet.getAddress().length)
                + (mode == ReaderMode.lowLevel ? "000C" : "000D");
        logger.info("Set low-level API with command 0x" + cmd.toString());

        DatagramPacket sendPacket = new DatagramPacket(hexStringToByteArray(cmd),
                hexStringToByteArray(cmd).length, IPInet, 3041);
        byte[] receiveData = new byte[4];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.send(sendPacket);
        clientSocket.setSoTimeout(2000);
        clientSocket.receive(receivePacket);
        logger.info("Return: " + byteArrayToHexString(receivePacket.getData(), receivePacket.getData().length));

        if (byteArrayToHexString(receivePacket.getData(), receivePacket.getData().length).startsWith("810100"))
            return true;
        else
            return false;
    } catch (UnknownHostException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

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

public void wemoDiscovery() {
    logger.debug("wemoDiscovery() is called!");
    try {// ww w.j a v a2s  . 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.rifidi.edge.adapter.csl.util.CslRfidTagServer.java

private ReaderMode checkMode() {
    try {/*from   w  ww  . j  a  va2  s.  c  om*/

        InetAddress IPInet = InetAddress.getByName(this.IPAddress);

        // Set low-level API mode
        String cmd = "80" + byteArrayToHexString(IPInet.getAddress(), IPInet.getAddress().length) + "000E";
        logger.info("Check mode with command 0x" + cmd.toString());

        DatagramPacket sendPacket = new DatagramPacket(hexStringToByteArray(cmd),
                hexStringToByteArray(cmd).length, IPInet, 3041);
        byte[] receiveData = new byte[5];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.send(sendPacket);
        clientSocket.setSoTimeout(2000);
        clientSocket.receive(receivePacket);
        logger.info(String.format(
                "Return: " + byteArrayToHexString(receivePacket.getData(), receivePacket.getData().length)));

        if (byteArrayToHexString(receivePacket.getData(), receivePacket.getData().length)
                .startsWith("8101010E00"))
            return ReaderMode.highLevel;
        else if (byteArrayToHexString(receivePacket.getData(), receivePacket.getData().length)
                .startsWith("8101010E01"))
            return ReaderMode.lowLevel;
        else
            return null;
    } catch (UnknownHostException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.iiitd.networking.UDPMessenger.java

public void startMessageReceiver() {
    Runnable receiver = new Runnable() {

        @Override/*  w  ww.  j  a  v a 2s .  c om*/
        public void run() {
            WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wim != null) {
                MulticastLock mcLock = wim.createMulticastLock(TAG);
                mcLock.acquire();
            }

            byte[] buffer = new byte[BUFFER_SIZE];
            DatagramPacket rPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket rSocket;

            try {
                rSocket = new MulticastSocket(MULTICAST_PORT);
            } catch (IOException e) {
                Log.d(DEBUG_TAG, "Impossible to create a new MulticastSocket on port " + MULTICAST_PORT);
                e.printStackTrace();
                return;
            }

            while (receiveMessages) {
                try {
                    rSocket.receive(rPacket);
                } catch (IOException e1) {
                    Log.d(DEBUG_TAG, "There was a problem receiving the incoming message.");
                    e1.printStackTrace();
                    continue;
                }

                if (!receiveMessages)
                    break;

                byte data[] = rPacket.getData();
                int i;
                for (i = 0; i < data.length; i++) {
                    if (data[i] == '\0')
                        break;
                }

                String messageText;

                try {
                    messageText = new String(data, 0, i, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    Log.d(DEBUG_TAG, "UTF-8 encoding is not supported. Can't receive the incoming message.");
                    e.printStackTrace();
                    continue;
                }

                try {
                    incomingMessage = new Message(messageText, rPacket.getAddress());
                } catch (IllegalArgumentException ex) {
                    Log.d(DEBUG_TAG, "There was a problem processing the message: " + messageText);
                    ex.printStackTrace();
                    continue;
                }

                incomingMessageHandler.post(getIncomingMessageAnalyseRunnable());
            }
        }

    };

    receiveMessages = true;
    if (receiverThread == null)
        receiverThread = new Thread(receiver);

    if (!receiverThread.isAlive())
        receiverThread.start();
}