Example usage for io.netty.util NetUtil LOCALHOST

List of usage examples for io.netty.util NetUtil LOCALHOST

Introduction

In this page you can find the example usage for io.netty.util NetUtil LOCALHOST.

Prototype

InetAddress LOCALHOST

To view the source code for io.netty.util NetUtil LOCALHOST.

Click Source Link

Document

The InetAddress that represents the loopback address.

Usage

From source file:dorkbox.network.connection.EndPoint.java

License:Apache License

/**
 * @param type this is either "Client" or "Server", depending on who is creating this endpoint.
 * @param config these are the specific connection options
 *
 * @throws SecurityException if unable to initialize/generate ECC keys
 */// w  w  w  .  j  ava 2 s  .  c o m
public EndPoint(Class<? extends EndPoint> type, final Configuration config) throws SecurityException {
    super(type);
    this.config = config;

    // make sure that 'localhost' is ALWAYS our specific loopback IP address
    if (config.host != null && (config.host.equals("localhost") || config.host.startsWith("127."))) {
        // localhost IP might not always be 127.0.0.1
        config.host = NetUtil.LOCALHOST.getHostAddress();
    }

    // serialization stuff
    if (config.serialization != null) {
        serializationManager = config.serialization;
    } else {
        serializationManager = Serialization.DEFAULT();
    }

    // setup our RMI serialization managers. Can only be called once
    rmiEnabled = serializationManager.initRmiSerialization();

    // The registration wrapper permits the registration process to access protected/package fields/methods, that we don't want
    // to expose to external code. "this" escaping can be ignored, because it is benign.
    //noinspection ThisEscapedInObjectConstruction
    registrationWrapper = new RegistrationWrapper(this, logger);

    // we have to be able to specify WHAT property store we want to use, since it can change!
    if (config.settingsStore == null) {
        propertyStore = new PropertyStore();
    } else {
        propertyStore = config.settingsStore;
    }

    propertyStore.init(serializationManager, null);

    // null it out, since it is sensitive!
    config.settingsStore = null;

    if (!(propertyStore instanceof NullSettingsStore)) {
        // initialize the private/public keys used for negotiating ECC handshakes
        // these are ONLY used for IP connections. LOCAL connections do not need a handshake!
        ECPrivateKeyParameters privateKey = propertyStore.getPrivateKey();
        ECPublicKeyParameters publicKey = propertyStore.getPublicKey();

        if (privateKey == null || publicKey == null) {
            try {
                // seed our RNG based off of this and create our ECC keys
                byte[] seedBytes = Entropy
                        .get("There are no ECC keys for the " + type.getSimpleName() + " yet");
                SecureRandom secureRandom = new SecureRandom(seedBytes);
                secureRandom.nextBytes(seedBytes);

                logger.debug("Now generating ECC (" + CryptoECC.curve25519 + ") keys. Please wait!");
                AsymmetricCipherKeyPair generateKeyPair = CryptoECC.generateKeyPair(CryptoECC.curve25519,
                        secureRandom);

                privateKey = (ECPrivateKeyParameters) generateKeyPair.getPrivate();
                publicKey = (ECPublicKeyParameters) generateKeyPair.getPublic();

                // save to properties file
                propertyStore.savePrivateKey(privateKey);
                propertyStore.savePublicKey(publicKey);

                logger.debug("Done with ECC keys!");
            } catch (Exception e) {
                String message = "Unable to initialize/generate ECC keys. FORCED SHUTDOWN.";
                logger.error(message);
                throw new SecurityException(message);
            }
        }

        this.privateKey = privateKey;
        this.publicKey = publicKey;
    } else {
        this.privateKey = null;
        this.publicKey = null;
    }

    secureRandom = new SecureRandom(propertyStore.getSalt());

    // we don't care about un-instantiated/constructed members, since the class type is the only interest.
    //noinspection unchecked
    connectionManager = new ConnectionManager(type.getSimpleName(), connection0(null, null).getClass());

    if (rmiEnabled) {
        rmiGlobalBridge = new RmiBridge(logger, true);
    } else {
        rmiGlobalBridge = null;
    }

    Logger readLogger = LoggerFactory.getLogger(type.getSimpleName() + ".READ");
    Logger writeLogger = LoggerFactory.getLogger(type.getSimpleName() + ".WRITE");
    serializationManager.finishInit(readLogger, writeLogger);
}

From source file:dorkbox.network.connection.wrapper.ChannelNetworkWrapper.java

License:Apache License

public ChannelNetworkWrapper(final MetaChannel metaChannel, final InetSocketAddress remoteAddress) {

    this.sessionId = metaChannel.sessionId;
    this.isLoopback = remoteAddress.getAddress().equals(NetUtil.LOCALHOST);

    if (metaChannel.tcpChannel != null) {
        this.tcp = new ChannelNetwork(metaChannel.tcpChannel);
    } else {/*w w  w. j  a  v  a 2  s.  com*/
        this.tcp = null;
    }

    if (metaChannel.udpChannel != null) {
        this.udp = new ChannelNetwork(metaChannel.udpChannel);
    } else {
        this.udp = null;
    }

    this.remoteAddress = remoteAddress.getAddress().getHostAddress();
    this.remotePublicKeyChanged = metaChannel.changedRemoteKey;

    // AES key & IV (only for networked connections)
    aesKey = metaChannel.aesKey;
    aesIV = metaChannel.aesIV;

    cryptoParameters = new FastThreadLocal<ParametersWithIV>() {
        @Override
        public ParametersWithIV initialValue() {
            return new ParametersWithIV(new KeyParameter(aesKey), aesIV);
        }
    };
}

From source file:reactor.io.net.impl.netty.udp.NettyDatagramServer.java

License:Apache License

public NettyDatagramServer(@Nonnull Environment env, @Nonnull Dispatcher dispatcher,
        @Nullable InetSocketAddress listenAddress, @Nullable final NetworkInterface multicastInterface,
        @Nonnull final ServerSocketOptions options, @Nullable Codec<Buffer, IN, OUT> codec) {
    super(env, dispatcher, listenAddress, multicastInterface, options, codec);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {/*w  ww . j  a v a  2s .co  m*/
        this.nettyOptions = null;
    }

    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        int ioThreadCount = getDefaultEnvironment().getIntProperty("reactor.udp.ioThreadCount",
                Environment.PROCESSORS);
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-udp-io"));
    }

    final InternetProtocolFamily family = toNettyFamily(options.protocolFamily());

    this.bootstrap = new Bootstrap().group(ioGroup).option(ChannelOption.SO_RCVBUF, options.rcvbuf())
            .option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr()).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.timeout())
            .channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel() {
                    return new NioDatagramChannel(family);
                }
            });

    if (null != listenAddress) {
        bootstrap.localAddress(listenAddress);
    } else {
        bootstrap.localAddress(NetUtil.LOCALHOST, 3000);
    }
    if (null != multicastInterface) {
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }
}

From source file:reactor.io.net.netty.udp.NettyDatagramServer.java

License:Apache License

public NettyDatagramServer(@Nonnull Environment env, @Nonnull EventBus reactor,
        @Nullable InetSocketAddress listenAddress, @Nullable final NetworkInterface multicastInterface,
        @Nonnull final ServerSocketOptions options, @Nullable Codec<Buffer, IN, OUT> codec,
        Collection<Consumer<NetChannel<IN, OUT>>> consumers) {
    super(env, reactor, listenAddress, multicastInterface, options, codec, consumers);

    if (options instanceof NettyServerSocketOptions) {
        this.nettyOptions = (NettyServerSocketOptions) options;
    } else {//from w  w w. j  a  va  2  s .c o m
        this.nettyOptions = null;
    }

    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        this.ioGroup = nettyOptions.eventLoopGroup();
    } else {
        int ioThreadCount = env.getProperty("reactor.udp.ioThreadCount", Integer.class, Environment.PROCESSORS);
        this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-udp-io"));
    }

    final NettyNetChannelInboundHandler inboundHandler = new NettyNetChannelInboundHandler() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            super.channelRead(ctx, ((DatagramPacket) msg).content());
        }
    };

    this.bootstrap = new Bootstrap().group(ioGroup).option(ChannelOption.SO_RCVBUF, options.rcvbuf())
            .option(ChannelOption.SO_SNDBUF, options.sndbuf())
            .option(ChannelOption.SO_REUSEADDR, options.reuseAddr())
            .channelFactory(new ChannelFactory<Channel>() {
                @Override
                public Channel newChannel() {
                    final NioDatagramChannel ch = new NioDatagramChannel();
                    DatagramChannelConfig config = ch.config();
                    config.setReceiveBufferSize(options.rcvbuf());
                    config.setSendBufferSize(options.sndbuf());
                    config.setReuseAddress(options.reuseAddr());

                    if (null != multicastInterface) {
                        config.setNetworkInterface(multicastInterface);
                    }

                    if (null != nettyOptions && null != nettyOptions.pipelineConfigurer()) {
                        nettyOptions.pipelineConfigurer().accept(ch.pipeline());
                    }

                    ch.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (log.isInfoEnabled()) {
                                log.info("CLOSE {}", ch);
                            }
                            close(ch);
                        }
                    });

                    netChannel = (NettyNetChannel<IN, OUT>) select(ch);
                    inboundHandler.setNetChannel(netChannel);

                    ch.pipeline().addLast(new ChannelOutboundHandlerAdapter() {
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                throws Exception {
                            super.write(ctx, msg, promise);
                        }
                    });

                    return ch;
                }
            }).handler(inboundHandler);

    if (null != listenAddress) {
        bootstrap.localAddress(listenAddress);
    } else {
        bootstrap.localAddress(NetUtil.LOCALHOST, 3000);
    }
    if (null != multicastInterface) {
        bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface);
    }
}

From source file:reactor.ipc.netty.http.server.HttpServer.java

License:Open Source License

/**
 * Build a simple Netty HTTP server listening on 127.0.0.1 and 12012
 *
 * @return a simple HTTP Server/*w w  w.  j  ava2 s.co m*/
 */
public static HttpServer create() {
    return create(NetUtil.LOCALHOST.getHostAddress());
}

From source file:reactor.ipc.netty.options.ClientOptions.java

License:Open Source License

/**
 * The localhost port to which this client should connect.
 *
 * @param port The port to connect to./*from w  w  w.  jav a 2 s .c o m*/
 *
 * @return {@literal this}
 */
public ClientOptions connect(int port) {
    return connect(new InetSocketAddress(NetUtil.LOCALHOST.getHostAddress(), port));
}

From source file:reactor.ipc.netty.options.HttpServerOptions.java

License:Open Source License

/**
 * Create a server builder for listening on the current default localhost address
 * (inet4 or inet6) and {@code port}.//from   w ww  .ja  va  2 s  .  c  o  m
 * @param port the port to listen on.
 * @return a new server builder
 */
public static HttpServerOptions on(int port) {
    return on(NetUtil.LOCALHOST.getHostAddress(), port);
}

From source file:reactor.ipc.netty.tcp.TcpClient.java

License:Open Source License

/**
 * Bind a new TCP client to the localhost on port 12012. The default client
 * implementation is scanned from the classpath on Class init.
 * <p> The type of emitted data or received data is {@link ByteBuf}
 *
 * @return a new {@link TcpClient}//w ww  . jav  a2  s.c o  m
 */
public static TcpClient create() {
    return create(NetUtil.LOCALHOST.getHostAddress());
}

From source file:reactor.ipc.netty.tcp.TcpClient.java

License:Open Source License

/**
 * Bind a new TCP client to "loopback" on the the specified port. The default client
 * <p> The type of emitted data or received data is {@link ByteBuf}
 *
 * @param port the port to connect to on "loopback"
 * <p>//from   w ww .  j a  va 2s. c  o m
 * a new {@link TcpClient}
 */
public static TcpClient create(int port) {
    return create(NetUtil.LOCALHOST.getHostAddress(), port);
}

From source file:reactor.ipc.netty.tcp.TcpServer.java

License:Open Source License

/**
 * Bind a new TCP server to "loopback" on port {@literal 12012}.
 * Handlers will run on the same thread they have beem receiving IO events.
 * <p> The type of emitted data or received data is {@link ByteBuf}
 *
 * @return a new {@link TcpServer}//from  w  w  w .ja va2 s  .com
 */
public static TcpServer create() {
    return create(NetUtil.LOCALHOST.getHostAddress());
}