Example usage for io.netty.util NetUtil createByteArrayFromIpAddressString

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

Introduction

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

Prototype

public static byte[] createByteArrayFromIpAddressString(String ipAddressString) 

Source Link

Document

Creates an byte[] based on an ipAddressString.

Usage

From source file:com.linecorp.armeria.client.endpoint.dns.DnsAddressEndpointGroupTest.java

License:Apache License

private static DnsRecord newAddressRecord(String name, String ipAddr) {
    return new DefaultDnsRawRecord(name, NetUtil.isValidIpV4Address(ipAddr) ? A : AAAA, 60,
            Unpooled.wrappedBuffer(NetUtil.createByteArrayFromIpAddressString(ipAddr)));
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsAddressEndpointGroupTest.java

License:Apache License

private static DnsRecord newCompatibleAddressRecord(String name, String ipV4Addr) {
    final ByteBuf content = Unpooled.buffer();
    content.writeZero(12);//from   www .  j ava  2  s . co  m
    content.writeBytes(NetUtil.createByteArrayFromIpAddressString(ipV4Addr));
    return new DefaultDnsRawRecord(name, AAAA, 60, content);
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsAddressEndpointGroupTest.java

License:Apache License

private static DnsRecord newMappedAddressRecord(String name, String ipV4Addr) {
    final ByteBuf content = Unpooled.buffer();
    content.writeZero(10);//from  w w  w .j  a  v a  2s .co m
    content.writeShort(0xFFFF);
    content.writeBytes(NetUtil.createByteArrayFromIpAddressString(ipV4Addr));
    return new DefaultDnsRawRecord(name, AAAA, 60, content);
}

From source file:com.linecorp.armeria.client.HttpSessionChannelFactory.java

License:Apache License

private static InetSocketAddress toRemoteAddress(PoolKey key) throws UnknownHostException {
    final InetSocketAddress remoteAddress;
    final String ipAddr = key.ipAddr();
    if (ipAddr == null) {
        remoteAddress = InetSocketAddress.createUnresolved(key.host(), key.port());
    } else {//from  ww  w. j  a  v a2s  .com
        final InetAddress inetAddr = InetAddress.getByAddress(key.host(),
                NetUtil.createByteArrayFromIpAddressString(ipAddr));
        remoteAddress = new InetSocketAddress(inetAddr, key.port());
    }
    return remoteAddress;
}

From source file:com.linecorp.armeria.spring.ArmeriaAutoConfiguration.java

License:Apache License

private static void configurePorts(ArmeriaSettings armeriaSettings, ServerBuilder server) {
    if (armeriaSettings.getPorts().isEmpty()) {
        server.port(new ServerPort(DEFAULT_PORT.getPort(), DEFAULT_PORT.getProtocol()));
        return;/*from   www .  j av  a 2 s.  co m*/
    }

    for (Port p : armeriaSettings.getPorts()) {
        final String ip = p.getIp();
        final String iface = p.getIface();
        final int port = p.getPort();
        final SessionProtocol proto = p.getProtocol();

        if (ip == null) {
            if (iface == null) {
                server.port(new ServerPort(port, proto));
            } else {
                try {
                    final Enumeration<InetAddress> e = NetworkInterface.getByName(iface).getInetAddresses();
                    while (e.hasMoreElements()) {
                        server.port(new ServerPort(new InetSocketAddress(e.nextElement(), port), proto));
                    }
                } catch (SocketException e) {
                    throw new IllegalStateException("Failed to find an iface: " + iface, e);
                }
            }
        } else if (iface == null) {
            if (NetUtil.isValidIpV4Address(ip) || NetUtil.isValidIpV6Address(ip)) {
                final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(ip);
                try {
                    server.port(new ServerPort(new InetSocketAddress(InetAddress.getByAddress(bytes), port),
                            proto));
                } catch (UnknownHostException e) {
                    // Should never happen.
                    throw new Error(e);
                }
            } else {
                throw new IllegalStateException("invalid IP address: " + ip);
            }
        } else {
            throw new IllegalStateException("A port cannot have both IP and iface: " + p);
        }
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java

License:Apache License

/**
 * Hook designed for extensibility so one can pass a different cache on each resolution attempt
 * instead of using the global one.//from  w ww  .  j a  v  a  2 s  .c o m
 */
protected void doResolve(String inetHost, Promise<InetAddress> promise, DnsCache resolveCache)
        throws Exception {
    final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost);
    if (bytes != null) {
        // The inetHost is actually an ipaddress.
        promise.setSuccess(InetAddress.getByAddress(bytes));
        return;
    }

    final String hostname = hostname(inetHost);

    InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
    if (hostsFileEntry != null) {
        promise.setSuccess(hostsFileEntry);
        return;
    }

    if (!doResolveCached(hostname, promise, resolveCache)) {
        doResolveUncached(hostname, promise, resolveCache);
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java

License:Apache License

/**
 * Hook designed for extensibility so one can pass a different cache on each resolution attempt
 * instead of using the global one./*from   ww w. jav  a2 s  . co  m*/
 */
protected void doResolveAll(String inetHost, Promise<List<InetAddress>> promise, DnsCache resolveCache)
        throws Exception {

    final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost);
    if (bytes != null) {
        // The unresolvedAddress was created via a String that contains an ipaddress.
        promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes)));
        return;
    }

    final String hostname = hostname(inetHost);

    InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
    if (hostsFileEntry != null) {
        promise.setSuccess(Collections.singletonList(hostsFileEntry));
        return;
    }

    if (!doResolveAllCached(hostname, promise, resolveCache)) {
        doResolveAllUncached(hostname, promise, resolveCache);
    }
}

From source file:io.vertx.core.impl.HostnameResolver.java

License:Open Source License

public HostnameResolver(VertxImpl vertx, HostnameResolverOptions options) {
    DnsNameResolverBuilder builder = new DnsNameResolverBuilder(vertx.createEventLoopContext(null, null,
            new JsonObject(), Thread.currentThread().getContextClassLoader()).nettyEventLoop());
    builder.channelFactory(NioDatagramChannel::new);
    if (options != null) {
        List<String> dnsServers = options.getServers();
        if (dnsServers != null && dnsServers.size() > 0) {
            List<InetSocketAddress> serverList = new ArrayList<>();
            for (String dnsServer : dnsServers) {
                int sep = dnsServer.indexOf(':');
                String ipAddress;
                int port;
                if (sep != -1) {
                    ipAddress = dnsServer.substring(0, sep);
                    port = Integer.parseInt(dnsServer.substring(sep + 1));
                } else {
                    ipAddress = dnsServer;
                    port = 53;// w  w w.java  2 s  .c o  m
                }
                try {
                    serverList.add(new InetSocketAddress(
                            InetAddress.getByAddress(NetUtil.createByteArrayFromIpAddressString(ipAddress)),
                            port));
                } catch (UnknownHostException e) {
                    throw new VertxException(e);
                }
            }
            DnsServerAddresses nameServerAddresses = DnsServerAddresses.sequential(serverList);
            builder.nameServerAddresses(nameServerAddresses);
        }
        builder.optResourceEnabled(options.isOptResourceEnabled());
        builder.ttl(options.getCacheMinTimeToLive(), options.getCacheMaxTimeToLive());
        builder.negativeTtl(options.getCacheNegativeTimeToLive());
        builder.queryTimeoutMillis(options.getQueryTimeout());
        builder.maxQueriesPerResolve(options.getMaxQueries());
        builder.recursionDesired(options.getRdFlag());
    }
    this.resolver = builder.build();
    this.vertx = vertx;
}

From source file:io.vertx.core.impl.resolver.DnsResolverProvider.java

License:Open Source License

public DnsResolverProvider(VertxImpl vertx, AddressResolverOptions options) {
    List<String> dnsServers = options.getServers();
    List<InetSocketAddress> serverList = new ArrayList<>();
    if (dnsServers != null && dnsServers.size() > 0) {
        for (String dnsServer : dnsServers) {
            int sep = dnsServer.indexOf(':');
            String ipAddress;// ww w  .j ava  2s  .com
            int port;
            if (sep != -1) {
                ipAddress = dnsServer.substring(0, sep);
                port = Integer.parseInt(dnsServer.substring(sep + 1));
            } else {
                ipAddress = dnsServer;
                port = 53;
            }
            try {
                serverList.add(new InetSocketAddress(
                        InetAddress.getByAddress(NetUtil.createByteArrayFromIpAddressString(ipAddress)), port));
            } catch (UnknownHostException e) {
                throw new VertxException(e);
            }
        }
    } else {
        DnsServerAddressStream stream = DnsServerAddresses.defaultAddresses().stream();
        Set<InetSocketAddress> all = new HashSet<>();
        while (true) {
            InetSocketAddress address = stream.next();
            if (all.contains(address)) {
                break;
            }
            serverList.add(address);
            all.add(address);
        }
    }
    DnsServerAddresses nameServerAddresses = options.isRotateServers()
            ? DnsServerAddresses.rotational(serverList)
            : DnsServerAddresses.sequential(serverList);

    Map<String, InetAddress> entries;
    if (options.getHostsPath() != null) {
        File file = vertx.resolveFile(options.getHostsPath()).getAbsoluteFile();
        try {
            if (!file.exists() || !file.isFile()) {
                throw new IOException();
            }
            entries = HostsFileParser.parse(file);
        } catch (IOException e) {
            throw new VertxException("Cannot read hosts file " + file.getAbsolutePath());
        }
    } else if (options.getHostsValue() != null) {
        try {
            entries = HostsFileParser.parse(new StringReader(options.getHostsValue().toString()));
        } catch (IOException e) {
            throw new VertxException("Cannot read hosts config ", e);
        }
    } else {
        entries = HostsFileParser.parseSilently();
    }

    this.vertx = vertx;
    this.resolverGroup = new AddressResolverGroup<InetSocketAddress>() {

        @Override
        protected io.netty.resolver.AddressResolver<InetSocketAddress> newResolver(EventExecutor executor)
                throws Exception {

            DnsAddressResolverGroup group = new DnsAddressResolverGroup(NioDatagramChannel.class,
                    nameServerAddresses) {
                @Override
                protected NameResolver<InetAddress> newNameResolver(EventLoop eventLoop,
                        ChannelFactory<? extends DatagramChannel> channelFactory,
                        DnsServerAddresses nameServerAddresses) throws Exception {
                    DnsNameResolverBuilder builder = new DnsNameResolverBuilder((EventLoop) executor);
                    builder.hostsFileEntriesResolver(inetHost -> {
                        InetAddress addr = entries.get(inetHost);
                        if (addr == null) {
                            addr = entries.get(inetHost.toLowerCase(Locale.ENGLISH));
                        }
                        return addr;
                    });
                    builder.channelType(NioDatagramChannel.class);
                    builder.nameServerAddresses(nameServerAddresses);
                    builder.optResourceEnabled(options.isOptResourceEnabled());
                    builder.ttl(options.getCacheMinTimeToLive(), options.getCacheMaxTimeToLive());
                    builder.negativeTtl(options.getCacheNegativeTimeToLive());
                    builder.queryTimeoutMillis(options.getQueryTimeout());
                    builder.maxQueriesPerResolve(options.getMaxQueries());
                    builder.recursionDesired(options.getRdFlag());
                    if (options.getSearchDomains() != null) {
                        builder.searchDomains(options.getSearchDomains());
                        int ndots = options.getNdots();
                        if (ndots == -1) {
                            ndots = AddressResolver.DEFAULT_NDOTS_RESOLV_OPTION;
                        }
                        builder.ndots(ndots);
                    }
                    return builder.build();
                }
            };

            io.netty.resolver.AddressResolver<InetSocketAddress> resolver = group.getResolver(executor);
            resolvers.add(new ResolverRegistration(resolver, (EventLoop) executor));

            return resolver;
        }
    };
}

From source file:org.redisson.client.handler.RedisChannelInitializer.java

License:Apache License

private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
    if (!config.getAddress().isSsl()) {
        return;/*from w w w . j a  va  2s.  c o  m*/
    }

    io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK;
    if (config.getSslProvider() == SslProvider.OPENSSL) {
        provided = io.netty.handler.ssl.SslProvider.OPENSSL;
    }

    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided);
    if (config.getSslTruststore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        InputStream stream = config.getSslTruststore().openStream();
        try {
            char[] password = null;
            if (config.getSslTruststorePassword() != null) {
                password = config.getSslTruststorePassword().toCharArray();
            }
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContextBuilder.trustManager(trustManagerFactory);
    }

    if (config.getSslKeystore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        InputStream stream = config.getSslKeystore().openStream();
        char[] password = null;
        if (config.getSslKeystorePassword() != null) {
            password = config.getSslKeystorePassword().toCharArray();
        }
        try {
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        sslContextBuilder.keyManager(keyManagerFactory);
    }

    SSLParameters sslParams = new SSLParameters();
    if (config.isSslEnableEndpointIdentification()) {
        // TODO remove for JDK 1.7+
        try {
            Method method = sslParams.getClass().getDeclaredMethod("setEndpointIdentificationAlgorithm",
                    String.class);
            method.invoke(sslParams, "HTTPS");
        } catch (Exception e) {
            throw new SSLException(e);
        }
    } else {
        if (config.getSslTruststore() == null) {
            sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        }
    }

    SslContext sslContext = sslContextBuilder.build();
    String hostname = config.getSslHostname();
    if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) {
        hostname = config.getAddress().getHost();
    }

    SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort());
    sslEngine.setSSLParameters(sslParams);

    SslHandler sslHandler = new SslHandler(sslEngine);
    ch.pipeline().addLast(sslHandler);
    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

        volatile boolean sslInitDone;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            if (sslInitDone) {
                super.channelActive(ctx);
            }
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) {
                SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt;
                if (e.isSuccess()) {
                    sslInitDone = true;
                    ctx.fireChannelActive();
                } else {
                    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
                    connection.getConnectionPromise().tryFailure(e.cause());
                }
            }

            super.userEventTriggered(ctx, evt);
        }

    });
}