List of usage examples for java.net MulticastSocket bind
public synchronized void bind(SocketAddress addr) throws SocketException
From source file:net.sbbi.upnp.Discovery.java
/** * Sends an SSDP search message on the network * @param src the sender ip/* w ww.ja v a2 s . com*/ * @param ttl the time to live * @param mx the mx field * @param searchTarget the search target * @throws IOException if some IO errors occurs during search */ public static void sendSearchMessage(InetAddress src, int ttl, int mx, String searchTarget) throws IOException { int bindPort = DEFAULT_SSDP_SEARCH_PORT; String port = System.getProperty("net.sbbi.upnp.Discovery.bindPort"); if (port != null) { bindPort = Integer.parseInt(port); } InetSocketAddress adr = new InetSocketAddress(InetAddress.getByName(Discovery.SSDP_IP), Discovery.SSDP_PORT); java.net.MulticastSocket skt = new java.net.MulticastSocket(null); skt.bind(new InetSocketAddress(src, bindPort)); skt.setTimeToLive(ttl); StringBuffer packet = new StringBuffer(); packet.append("M-SEARCH * HTTP/1.1\r\n"); packet.append("HOST: 239.255.255.250:1900\r\n"); packet.append("MAN: \"ssdp:discover\"\r\n"); packet.append("MX: ").append(mx).append("\r\n"); packet.append("ST: ").append(searchTarget).append("\r\n").append("\r\n"); if (log.isDebugEnabled()) log.debug("Sending discovery message on 239.255.255.250:1900 multicast address form ip " + src.getHostAddress() + ":\n" + packet.toString()); String toSend = packet.toString(); byte[] pk = toSend.getBytes(); skt.send(new DatagramPacket(pk, pk.length, adr)); skt.disconnect(); skt.close(); }
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. *//*ww w.j a v a2 s . co 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.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java
public void sendWemoDiscoveryMessage() { logger.debug("wemoDiscovery() is called!"); try {// w w w . j ava 2s. c o 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.openhab.binding.wemo.internal.WemoBinding.java
public void wemoDiscovery() { logger.debug("wemoDiscovery() is called!"); try {/*from www. j a v a2 s . c om*/ 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); } }