Example usage for java.net MulticastSocket setReuseAddress

List of usage examples for java.net MulticastSocket setReuseAddress

Introduction

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

Prototype

public synchronized void setReuseAddress(boolean on) throws SocketException 

Source Link

Document

Enable/disable the SO_REUSEADDR socket option.

Usage

From source file:net.pms.network.UPNPHelper.java

/**
 * Gets the new multicast socket./*from  ww w. j  a v a2 s  .  c o m*/
 *
 * @return the new multicast socket
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static MulticastSocket getNewMulticastSocket() throws IOException {
    NetworkInterface networkInterface = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName();

    if (networkInterface == null) {
        networkInterface = PMS.get().getServer().getNetworkInterface();
    }

    if (networkInterface == null) {
        throw new IOException("No usable network interface found for UPnP multicast");
    }

    List<InetAddress> usableAddresses = new ArrayList<InetAddress>();
    List<InetAddress> networkInterfaceAddresses = Collections.list(networkInterface.getInetAddresses());

    for (InetAddress inetAddress : networkInterfaceAddresses) {
        if (inetAddress != null && inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
            usableAddresses.add(inetAddress);
        }
    }

    if (usableAddresses.isEmpty()) {
        throw new IOException("No usable addresses found for UPnP multicast");
    }

    InetSocketAddress localAddress = new InetSocketAddress(usableAddresses.get(0), 0);
    MulticastSocket ssdpSocket = new MulticastSocket(localAddress);
    ssdpSocket.setReuseAddress(true);

    logger.trace(
            "Sending message from multicast socket on network interface: " + ssdpSocket.getNetworkInterface());
    logger.trace("Multicast socket is on interface: " + ssdpSocket.getInterface());
    ssdpSocket.setTimeToLive(32);
    logger.trace("Socket Timeout: " + ssdpSocket.getSoTimeout());
    logger.trace("Socket TTL: " + ssdpSocket.getTimeToLive());
    return ssdpSocket;
}

From source file:com.summit.jbeacon.beacons.MultiCastResourceBeacon.java

/**
 * refresh the resources that are available.
 * @throws MultiCastResourceBeaconException if
 * the data fails to be refreshed// w  ww .j a  va 2s . c o m
 */
public final void refreshData() throws MultiCastResourceBeaconException {
    while (!listenerThread.isRunning()) {
        try {
            log.debug("Waiting for server to start.");
            Thread.sleep(threadSleep);
        } catch (InterruptedException ex) {
            log.warn("Thread death while waiting for listener to run.");
        }

    }
    log.info("Attempting to refresh data.");
    if (listeningSocket == null) {
        throw new MultiCastResourceBeaconException(
                "Beacon is not " + "listening for responses. Initialize the " + "listener first!");
    }
    MulticastSocket s = null;
    try {
        s = new MulticastSocket();
        s.setReuseAddress(true);
    } catch (IOException ex) {
        throw new MultiCastResourceBeaconException("Error creating multicast socket...", ex);
    }

    String broadcastMessage = getBroadcastText() + " : " + getIp() + ":" + getHostName() + ":"
            + listeningSocket.getLocalPort();
    byte[] buf = broadcastMessage.getBytes();
    DatagramPacket pack = null;
    try {
        log.info("Multicast port: " + getGroupPort());
        log.info("Multicast group: " + getGroupAddress());
        pack = new DatagramPacket(buf, buf.length, InetAddress.getByName(getGroupAddress()), getGroupPort());
    } catch (UnknownHostException ex) {
        throw new MultiCastResourceBeaconException("Error creating datagram.", ex);
    }
    try {
        s.send(pack);
    } catch (IOException ex) {
        throw new MultiCastResourceBeaconException("Error sending message.", ex);
    }
    s.close();
}

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   w  w w .ja  v  a  2 s  . c om*/
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:net.pms.network.UPNPHelper.java

/**
 * Starts up two threads: one to broadcast UPnP ALIVE messages and another
 * to listen for responses. // w  w w  .j  a v  a2s.c om
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void listen() throws IOException {
    Runnable rAlive = new Runnable() {
        @Override
        public void run() {
            int delay = 10000;

            while (true) {
                sleep(delay);
                sendAlive();

                // The first delay for sending an ALIVE message is 10 seconds,
                // the second delay is for 20 seconds. From then on, all other
                // delays are for 180 seconds.
                switch (delay) {
                case 10000:
                    delay = 20000;
                    break;
                case 20000:
                    delay = 180000;
                    break;
                }
            }
        }
    };

    aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender");
    aliveThread.start();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            boolean bindErrorReported = false;

            while (true) {
                MulticastSocket multicastSocket = null;

                try {
                    // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166
                    multicastSocket = new MulticastSocket(configuration.getUpnpPort());

                    if (bindErrorReported) {
                        logger.warn(
                                "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!");
                    }

                    NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName();

                    try {
                        // Setting the network interface will throw a SocketException on Mac OSX
                        // with Java 1.6.0_45 or higher, but if we don't do it some Windows
                        // configurations will not listen at all.
                        if (ni != null) {
                            multicastSocket.setNetworkInterface(ni);
                        } else if (PMS.get().getServer().getNetworkInterface() != null) {
                            multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface());
                            logger.trace("Setting multicast network interface: "
                                    + PMS.get().getServer().getNetworkInterface());
                        }
                    } catch (SocketException e) {
                        // Not setting the network interface will work just fine on Mac OSX.
                    }

                    multicastSocket.setTimeToLive(4);
                    multicastSocket.setReuseAddress(true);
                    InetAddress upnpAddress = getUPNPAddress();
                    multicastSocket.joinGroup(upnpAddress);

                    while (true) {
                        byte[] buf = new byte[1024];
                        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
                        multicastSocket.receive(receivePacket);

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

                        InetAddress address = receivePacket.getAddress();

                        if (s.startsWith("M-SEARCH")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            if (configuration.getIpFiltering().allowed(address)) {
                                logger.trace(
                                        "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]");

                                if (StringUtils.indexOf(s,
                                        "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:service:ContentDirectory:1");
                                }

                                if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) {
                                    sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
                                }

                                if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, "ssdp:all") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, PMS.get().usn()) > 0) {
                                    sendDiscover(remoteAddr, remotePort, PMS.get().usn());
                                }
                            }
                        } else if (s.startsWith("NOTIFY")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]");
                        }
                    }
                } catch (BindException e) {
                    if (!bindErrorReported) {
                        logger.error("Unable to bind to " + configuration.getUpnpPort()
                                + ", which means that PMS will not automatically appear on your renderer! "
                                + "This usually means that another program occupies the port. Please "
                                + "stop the other program and free up the port. "
                                + "PMS will keep trying to bind to it...[" + e.getMessage() + "]");
                    }

                    bindErrorReported = true;
                    sleep(5000);
                } catch (IOException e) {
                    logger.error("UPNP network exception", e);
                    sleep(1000);
                } finally {
                    if (multicastSocket != null) {
                        // Clean up the multicast socket nicely
                        try {
                            InetAddress upnpAddress = getUPNPAddress();
                            multicastSocket.leaveGroup(upnpAddress);
                        } catch (IOException e) {
                        }

                        multicastSocket.disconnect();
                        multicastSocket.close();
                    }
                }
            }
        }
    };

    listenerThread = new Thread(r, "UPNPHelper");
    listenerThread.start();
}

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

/**
 * Broadcasts a SSDP discovery message into the network to find provided
 * services./*from   w  w w.j av  a 2s. c o  m*/
 * 
 * @return The Socket the answers will arrive at.
 * @throws UnknownHostException
 * @throws IOException
 * @throws SocketException
 * @throws UnsupportedEncodingException
 */
private MulticastSocket sendDiscoveryBroacast()
        throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException {
    InetAddress multicastAddress = InetAddress.getByName("239.255.255.250");
    final int port = 1900;
    MulticastSocket socket = new MulticastSocket(port);
    socket.setReuseAddress(true);
    socket.setSoTimeout(130000);
    socket.joinGroup(multicastAddress);
    byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8");
    DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress,
            port);
    socket.send(datagramPacket);
    return socket;
}