Example usage for io.netty.channel ChannelOption IP_MULTICAST_IF

List of usage examples for io.netty.channel ChannelOption IP_MULTICAST_IF

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption IP_MULTICAST_IF.

Prototype

ChannelOption IP_MULTICAST_IF

To view the source code for io.netty.channel ChannelOption IP_MULTICAST_IF.

Click Source Link

Usage

From source file:com.andrewkroh.cicso.rtp.NettyRtpSession.java

License:Apache License

public NettyRtpSession(final InetSocketAddress bindAddress, final NetworkInterface multicastInterface,
        final InetAddress multicastGroup) {
    Preconditions.checkNotNull(bindAddress, "Must specify a bind address.");

    if (multicastGroup != null) {
        Preconditions.checkNotNull(multicastInterface,
                "When specifying the multicast group you must also " + "specify the multicast interface.");

        // Javadoc for Java 7 MulticastChannel states: The channel's
        // socket should be bound to the wildcard address. If the socket
        // is bound to a specific address, rather than the wildcard address
        // then it is implementation specific if multicast datagrams
        // are received by the socket.
        Preconditions.checkArgument(bindAddress.getAddress().isAnyLocalAddress(),
                "Must bind to wildcard address when using multicast.");
    }/*from w w  w.j av  a 2s.  com*/

    EventLoopGroup workerGroup = new NioEventLoopGroup(NUM_THREADS);

    bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_REUSEADDR, true)
            .localAddress(bindAddress).handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new RtpPacketHandler(NettyRtpSession.this));
                }
            });

    if (multicastGroup != null) {
        bootstrap.option(ChannelOption.IP_MULTICAST_TTL, MULTICAST_TTL);

        // All multicast traffic generated from this channel will be
        // output from this interface. If not specified it will use the OS
        // default which may be unpredicatable:
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }

    channel = (DatagramChannel) bootstrap.bind().syncUninterruptibly().channel();

    LOGGER.info("Session bound to: {}", channel.localAddress());

    if (multicastGroup != null) {
        channel.joinGroup(multicastGroup, multicastInterface, null).syncUninterruptibly();

        LOGGER.info("Session bound to multicast group {} on interface {}.", multicastGroup.getHostAddress(),
                multicastInterface.getDisplayName());
    } else {
        LOGGER.info("Session will not be a multicast listener because " + "no multicast group was specified.");
    }
}

From source file:com.andrewkroh.cisco.rtp.NettyRtpSessionTest.java

License:Apache License

/**
 * Creates the test client and binds it to a random IPv4 address.
 *///from   www.j av a  2s .c om
@Before
public void beforeTest() throws InterruptedException, UnknownHostException {
    clientHandler = new TestHandler();
    clientBootstrap = new Bootstrap();
    clientBootstrap.group(new NioEventLoopGroup()).channel(NioDatagramChannel.class)
            .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.IP_MULTICAST_IF, multicastInterface)
            .localAddress(TestUtils.getFreePort()).handler(clientHandler);

    clientChannel = (DatagramChannel) clientBootstrap.bind().sync().channel();

    rtpPacket = new RtpPacket();
    rtpPacket.setPayloadType(PAYLOAD_TYPE);
    rtpPacket.setRtpPayloadData(new byte[] { PACKET_PAYLOAD_DATA });
    rtpPacket.setTimestamp(TIMESTAMP);
}

From source file:com.barchart.netty.server.stream.MulticastTransceiver.java

License:BSD License

/**
 * Join the multicast group address using the network interface associated
 * with the given address./*from  w ww  .  j  av  a 2s . c o  m*/
 */
@Override
public ChannelFuture listen(final SocketAddress address) {

    if (pipelineInit == null) {
        throw new IllegalStateException("No pipeline initializer has been provided, server would do nothing");
    }

    // Kinda hacky, need to override bootstrap params based on passed
    // address

    final ChannelFuture future = bootstrap() //
            .option(ChannelOption.IP_MULTICAST_IF, bindInterface((InetSocketAddress) address)) //
            .localAddress(multicast.getPort()) //
            .remoteAddress(multicast) //
            .bind();

    future.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {

            if (future.isSuccess()) {

                final NioDatagramChannel channel = (NioDatagramChannel) future.channel();

                channel.joinGroup(multicast, channel.config().getOption(ChannelOption.IP_MULTICAST_IF));

            }

        }

    });

    serverChannels.add(future.channel());

    return future;

}

From source file:com.barchart.netty.server.stream.MulticastTransceiver.java

License:BSD License

@Override
public Future<MulticastTransceiver> shutdown() {

    for (final Channel c : serverChannels) {

        final NioDatagramChannel dc = (NioDatagramChannel) c;

        final InetSocketAddress multicast = dc.remoteAddress();

        dc.leaveGroup(multicast, dc.config().getOption(ChannelOption.IP_MULTICAST_IF));

    }//from   w w w.j a  va 2  s.  c  om

    return super.shutdown();

}

From source file:com.github.mrstampy.kitchensync.netty.Bootstrapper.java

License:Open Source License

/**
 * Multicast bootstrap, adding the IP_MULTICAST_IF=networkInterface option.
 *
 * @param <CHANNEL>//from   ww  w. j a  va2s  .  co  m
 *          the generic type
 * @param initializer
 *          the initializer
 * @param multicast
 *          the multicast
 * @param networkInterface
 *          the network interface
 * @param clazz
 *          the clazz
 * @return the bootstrap
 */
protected <CHANNEL extends DatagramChannel> Bootstrap multicastBootstrap(
        ChannelInitializer<DatagramChannel> initializer, InetSocketAddress multicast,
        NetworkInterface networkInterface, Class<? extends CHANNEL> clazz) {
    Bootstrap b = bootstrap(initializer, multicast.getPort(), clazz);

    b.option(ChannelOption.IP_MULTICAST_IF, networkInterface);

    return b;
}

From source file:com.heliosapm.shorthand.caster.broadcast.BroadcastListener.java

License:Open Source License

/**
 * Starts a listener on the passed socket address
 * @param isa The socket address to listen on
 * @param nic The network interface to listen on
 *///w  w  w  . j av  a2 s  . c  om
public void startListener(InetSocketAddress isa, NetworkInterface nic) {
    Channel channel = null;
    if (isa.getAddress().isMulticastAddress()) {
        channel = bootstrap.group(group).channel(NioDatagramChannel.class)
                //                 .option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.IP_MULTICAST_ADDR, isa.getAddress())
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new LoggingHandler(BroadcastListener.class, LogLevel.DEBUG));
                        pipeline.addLast(router);
                    }
                }).localAddress(isa).bind(isa.getPort()).syncUninterruptibly().channel();
        ((NioDatagramChannel) channel).joinGroup(isa, NetUtil.LOOPBACK_IF).syncUninterruptibly();

        //.bind(isa.getPort()).syncUninterruptibly().channel();
        log("Bound to Multicast [%s]", isa);
    } else {
        channel = bootstrap.group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true).handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new LoggingHandler(BroadcastListener.class, LogLevel.DEBUG));
                        pipeline.addLast(router);
                    }
                }).localAddress(isa).bind(isa).syncUninterruptibly().channel();
        log("Bound to Broadcast UDP [%s]", isa);
    }
    boundChannels.add(channel);

    //.bind().syncUninterruptibly().channel();
    boundChannels.add(channel);
    log("Started Broadcast Listener on [%s]", isa);

}

From source file:com.whizzosoftware.hobson.ssdp.SSDPPlugin.java

License:Open Source License

public void createSockets() {
    try {//from  www .ja  va  2s  .  c  o m
        logger.debug("Using network interface: {}; local address: {}", nic, localAddress);

        if (nic == null) {
            logger.error("Unable to determine local NIC; discovery may not work properly");
        }

        if (nic != null) {
            Bootstrap clientBootstrap = new Bootstrap().group(eventLoopGroup)
                    .channelFactory(new ChannelFactory<Channel>() {
                        @Override
                        public Channel newChannel() {
                            return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                        }
                    }).localAddress(groupAddress).option(ChannelOption.IP_MULTICAST_IF, nic)
                    .option(ChannelOption.SO_REUSEADDR, true).handler(new SSDPInboundHandler(this));

            clientBootstrap.bind().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    multicastChannel = (NioDatagramChannel) channelFuture.channel();
                    multicastChannel.joinGroup(groupAddress, nic);
                }
            });
        }

        Bootstrap serverBootstrap = new Bootstrap().group(eventLoopGroup)
                .channelFactory(new ChannelFactory<Channel>() {
                    @Override
                    public Channel newChannel() {
                        return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                    }
                }).localAddress(localAddress).option(ChannelOption.IP_MULTICAST_IF, nic)
                .option(ChannelOption.SO_REUSEADDR, true).handler(new SSDPInboundHandler(this));

        serverBootstrap.bind().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                localChannel = (NioDatagramChannel) channelFuture.channel();
                sendDiscoveryPacket();
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.atomix.cluster.messaging.impl.NettyBroadcastService.java

License:Apache License

private CompletableFuture<Void> bootstrapServer() {
    Bootstrap serverBootstrap = new Bootstrap().group(group)
            .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
            .handler(new SimpleChannelInboundHandler<Object>() {
                @Override//from  w  w  w.  j  av  a2 s .c o  m
                public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                    // Nothing will be sent.
                }
            }).option(ChannelOption.IP_MULTICAST_IF, iface).option(ChannelOption.SO_REUSEADDR, true);

    CompletableFuture<Void> future = new CompletableFuture<>();
    serverBootstrap.bind(localAddress).addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            serverChannel = f.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}

From source file:io.atomix.cluster.messaging.impl.NettyBroadcastService.java

License:Apache License

private CompletableFuture<Void> bootstrapClient() {
    Bootstrap clientBootstrap = new Bootstrap().group(group)
            .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
            .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                @Override//from w  ww.j ava2 s .  c  o m
                protected void channelRead0(ChannelHandlerContext context, DatagramPacket packet)
                        throws Exception {
                    byte[] payload = new byte[packet.content().readInt()];
                    packet.content().readBytes(payload);
                    Message message = SERIALIZER.decode(payload);
                    Set<Consumer<byte[]>> listeners = NettyBroadcastService.this.listeners
                            .get(message.subject());
                    if (listeners != null) {
                        for (Consumer<byte[]> listener : listeners) {
                            listener.accept(message.payload());
                        }
                    }
                }
            }).option(ChannelOption.IP_MULTICAST_IF, iface).option(ChannelOption.SO_REUSEADDR, true)
            .localAddress(localAddress.getPort());

    CompletableFuture<Void> future = new CompletableFuture<>();
    clientBootstrap.bind().addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            clientChannel = (DatagramChannel) f.channel();
            log.info("{} joining multicast group {} on port {}", localAddress.getHostName(),
                    groupAddress.getHostName(), groupAddress.getPort());
            clientChannel.joinGroup(groupAddress, iface).addListener(f2 -> {
                if (f2.isSuccess()) {
                    log.info("{} successfully joined multicast group {} on port {}", localAddress.getHostName(),
                            groupAddress.getHostName(), groupAddress.getPort());
                    future.complete(null);
                } else {
                    log.info("{} failed to join group {} on port {}", localAddress.getHostName(),
                            groupAddress.getHostName(), groupAddress.getPort());
                    future.completeExceptionally(f2.cause());
                }
            });
        } else {
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}

From source file:io.hekate.cluster.seed.multicast.MulticastSeedNodeProvider.java

License:Apache License

@Override
public void startDiscovery(String cluster, InetSocketAddress address) throws HekateException {
    log.info("Starting seed nodes discovery [cluster={}, {}]", cluster, ToString.formatProperties(this));

    SeedNode thisNode = new SeedNode(address, cluster);

    try {//from   w w w .  ja va2 s  .  c o  m
        NetworkInterface nif = selectMulticastInterface(address);

        try {
            synchronized (mux) {
                if (isRegistered()) {
                    throw new IllegalStateException(
                            "Multicast seed node provider is already registered with another address "
                                    + "[existing=" + localNode + ']');
                }

                ByteBuf discoveryMsg = prepareDiscovery(thisNode);

                ByteBuf seedNodeInfoBytes = prepareSeedNodeInfo(thisNode);

                localNode = thisNode;

                seedNodes = new HashSet<>();

                eventLoop = new NioEventLoopGroup(1, new HekateThreadFactory("SeedNodeMulticast"));

                // Prepare common bootstrap options.
                Bootstrap bootstrap = new Bootstrap();

                bootstrap.option(ChannelOption.SO_REUSEADDR, true);
                bootstrap.option(ChannelOption.IP_MULTICAST_TTL, ttl);
                bootstrap.option(ChannelOption.IP_MULTICAST_IF, nif);

                if (loopBackDisabled) {
                    bootstrap.option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, true);

                    if (DEBUG) {
                        log.debug("Setting {} option to true", ChannelOption.IP_MULTICAST_LOOP_DISABLED);
                    }
                }

                bootstrap.group(eventLoop);
                bootstrap.channelFactory(() -> new NioDatagramChannel(ipVer));

                // Create a sender channel (not joined to a multicast group).
                bootstrap.localAddress(0);
                bootstrap.handler(createSenderHandler(thisNode));

                ChannelFuture senderBind = bootstrap.bind();

                DatagramChannel localSender = (DatagramChannel) senderBind.channel();

                sender = localSender;

                senderBind.get();

                // Create a listener channel and join to a multicast group.
                bootstrap.localAddress(group.getPort());

                bootstrap.handler(createListenerHandler(thisNode, seedNodeInfoBytes));

                ChannelFuture listenerBind = bootstrap.bind();

                listener = (DatagramChannel) listenerBind.channel();

                listenerBind.get();

                log.info("Joining to a multicast group " + "[address={}, port={}, interface={}, ttl={}]",
                        AddressUtils.host(group), group.getPort(), nif.getName(), ttl);

                listener.joinGroup(group, nif).get();

                // Create a periodic task for discovery messages sending.
                discoveryFuture = eventLoop.scheduleWithFixedDelay(() -> {
                    if (DEBUG) {
                        log.debug("Sending discovery message [from={}]", thisNode);
                    }

                    DatagramPacket discovery = new DatagramPacket(discoveryMsg.copy(), group);

                    localSender.writeAndFlush(discovery);
                }, 0, interval, TimeUnit.MILLISECONDS);
            }
        } catch (ExecutionException e) {
            cleanup();

            throw new HekateException(
                    "Failed to start a multicast seed nodes discovery [node=" + thisNode + ']', e.getCause());
        }

        log.info("Will wait for seed nodes [timeout={}(ms)]", waitTime);

        Thread.sleep(waitTime);
    } catch (InterruptedException e) {
        cleanup();

        Thread.currentThread().interrupt();

        throw new HekateException(
                "Thread was interrupted while awaiting for multicast discovery [node=" + thisNode + ']', e);
    }

    log.info("Done waiting for seed nodes.");
}