Example usage for java.net StandardSocketOptions SO_REUSEADDR

List of usage examples for java.net StandardSocketOptions SO_REUSEADDR

Introduction

In this page you can find the example usage for java.net StandardSocketOptions SO_REUSEADDR.

Prototype

SocketOption SO_REUSEADDR

To view the source code for java.net StandardSocketOptions SO_REUSEADDR.

Click Source Link

Document

Re-use address.

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    NetworkInterface networkInterface = NetworkInterface.getByName("net1");

    DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET);

    dc.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    dc.bind(new InetSocketAddress(8080));
    dc.setOption(StandardSocketOptions.IP_MULTICAST_IF, networkInterface);

    InetAddress group = InetAddress.getByName("180.90.4.12");
    MembershipKey key = dc.join(group, networkInterface);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    MembershipKey key = null;// w  ww .j av a2 s. c  o m
    DatagramChannel client = DatagramChannel.open(StandardProtocolFamily.INET);

    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    client.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    client.bind(new InetSocketAddress(MULTICAST_PORT));
    client.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    InetAddress group = InetAddress.getByName(MULTICAST_IP);
    key = client.join(group, interf);

    System.out.println("Joined the   multicast  group:" + key);
    System.out.println("Waiting for a  message  from  the" + "  multicast group....");

    ByteBuffer buffer = ByteBuffer.allocate(1048);
    client.receive(buffer);
    buffer.flip();
    int limits = buffer.limit();
    byte bytes[] = new byte[limits];
    buffer.get(bytes, 0, limits);
    String msg = new String(bytes);

    System.out.format("Multicast Message:%s%n", msg);
    key.drop();
}

From source file:com.hurence.logisland.redis.service.ITRedisKeyValueCacheClientService.java

private int getAvailablePort() throws IOException {
    try (SocketChannel socket = SocketChannel.open()) {
        socket.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        socket.bind(new InetSocketAddress("localhost", 0));
        return socket.socket().getLocalPort();
    }//w  w w  . ja  v  a  2 s. c  om
}

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

/**
 * Constructs a {@link NatPmpController} object.
 * @param gatewayAddress address of router/gateway
 * @param listener a listener to listen for all NAT-PMP packets from this router
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 *//*from   ww w .j  a  v  a 2 s.co  m*/
public NatPmpController(InetAddress gatewayAddress, final NatPmpControllerListener listener)
        throws IOException {
    Validate.notNull(gatewayAddress);

    this.gateway = new InetSocketAddress(gatewayAddress, 5351);

    List<DatagramChannel> channels = new ArrayList<>(3);

    try {
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));

        ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET);
        ipv4MulticastChannel.configureBlocking(false);
        ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel);

        ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6);
        ipv6MulticastChannel.configureBlocking(false);
        ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        IOUtils.closeQuietly(ipv4MulticastChannel);
        IOUtils.closeQuietly(ipv6MulticastChannel);
        throw ioe;
    }

    channels.add(unicastChannel);
    channels.add(ipv4MulticastChannel);
    channels.add(ipv6MulticastChannel);

    this.communicator = new UdpCommunicator(channels);
    this.communicator.startAsync().awaitRunning();

    if (listener != null) {
        this.communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                CommunicationType type;
                if (channel == unicastChannel) {
                    type = CommunicationType.UNICAST;
                } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) {
                    type = CommunicationType.MULTICAST;
                } else {
                    return; // unknown, do nothing
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new ExternalAddressNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new UdpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new TcpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }
            }
        });
    }
}

From source file:com.offbynull.portmapper.pcp.PcpController.java

/**
 * Constructs a {@link PcpController} object.
 * @param random used to generate nonce values for requests
 * @param gatewayAddress address of router/gateway
 * @param selfAddress address of this machine on the interface that can talk to the router/gateway
 * @param listener a listener to listen for all PCP packets from this router
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 *//* w  ww .  j  av  a  2s. c  om*/
public PcpController(Random random, InetAddress gatewayAddress, InetAddress selfAddress,
        final PcpControllerListener listener) throws IOException {
    Validate.notNull(random);
    Validate.notNull(gatewayAddress);
    Validate.notNull(selfAddress);

    this.gateway = new InetSocketAddress(gatewayAddress, 5351);

    List<DatagramChannel> channels = new ArrayList<>(3);

    try {
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));

        ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET);
        ipv4MulticastChannel.configureBlocking(false);
        ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel);

        ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6);
        ipv6MulticastChannel.configureBlocking(false);
        ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        IOUtils.closeQuietly(ipv4MulticastChannel);
        IOUtils.closeQuietly(ipv6MulticastChannel);
        throw ioe;
    }

    channels.add(unicastChannel);
    channels.add(ipv4MulticastChannel);
    channels.add(ipv6MulticastChannel);

    this.communicator = new UdpCommunicator(channels);
    this.selfAddress = selfAddress;
    this.random = random;

    this.communicator.startAsync().awaitRunning();

    if (listener != null) {
        this.communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                CommunicationType type;
                if (channel == unicastChannel) {
                    type = CommunicationType.UNICAST;
                } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) {
                    type = CommunicationType.MULTICAST;
                } else {
                    return; // unknown, do nothing
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new AnnouncePcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new MapPcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new PeerPcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }
            }
        });
    }
}

From source file:org.apache.nifi.io.nio.ChannelListener.java

/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to/* ww w  .jav  a  2s.c o  m*/
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to " + receiveBufferSize
                    + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}

From source file:org.apache.nifi.io.nio.ChannelListener.java

private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port,
        final int receiveBufferSize) throws IOException {
    final DatagramChannel dChannel = DatagramChannel.open();
    dChannel.configureBlocking(false);// ww  w  .j a v a  2  s . c  o  m
    if (receiveBufferSize > 0) {
        dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to " + receiveBufferSize
                    + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    dChannel.bind(new InetSocketAddress(nicIPAddress, port));
    return dChannel;
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.DatagramChannelDispatcher.java

@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;/*  w w w  .  j a  va2 s.c  o  m*/
    datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);

    if (maxBufferSize > 0) {
        datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize
                    + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }

    // we don't have to worry about nicAddress being null here because InetSocketAddress already handles it
    datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    datagramChannel.socket().bind(new InetSocketAddress(nicAddress, port));

    // if a sending host and port were provided then connect to that specific address to only receive
    // datagrams from that host/port, otherwise we can receive datagrams from any host/port
    if (sendingHost != null && sendingPort != null) {
        datagramChannel.connect(new InetSocketAddress(sendingHost, sendingPort));
    }

    selector = Selector.open();
    datagramChannel.register(selector, SelectionKey.OP_READ);
}

From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

protected void doScan() {

    try {/*from   w  w w  .  j av  a 2  s . c  om*/

        if (!isScanning) {
            isScanning = true;
            if (selector != null) {
                selector.close();
            }

            if (broadcastChannel != null) {
                broadcastChannel.close();
            }

            selector = Selector.open();

            broadcastChannel = DatagramChannel.open(StandardProtocolFamily.INET)
                    .setOption(StandardSocketOptions.SO_REUSEADDR, true)
                    .setOption(StandardSocketOptions.SO_BROADCAST, true);
            broadcastChannel.configureBlocking(false);
            broadcastChannel.socket().setSoTimeout(BROADCAST_TIMEOUT);
            broadcastChannel.bind(new InetSocketAddress(BROADCAST_PORT));

            SelectionKey broadcastKey = broadcastChannel.register(selector,
                    SelectionKey.OP_READ | SelectionKey.OP_WRITE);

            networkJob = scheduler.schedule(networkRunnable, 0, TimeUnit.MILLISECONDS);

            source = UUID.randomUUID().getLeastSignificantBits() & (-1L >>> 32);
            logger.debug("The LIFX discovery service will use '{}' as source identifier",
                    Long.toString(source, 16));

            GetServiceRequest packet = new GetServiceRequest();
            packet.setSequence(SERVICE_REQUEST_SEQ_NO);
            packet.setSource(source);

            broadcastPacket(packet, broadcastKey);
        } else {
            logger.info("A discovery scan for LIFX light is already underway");
        }

    } catch (Exception e) {
        logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
    }

}