Search in sources :

Example 86 with Inet6Address

use of java.net.Inet6Address in project netxms by netxms.

the class AddAddressListElementDialog method okPressed.

/* (non-Javadoc)
	 * @see org.eclipse.jface.dialogs.Dialog#okPressed()
	 */
@Override
protected void okPressed() {
    try {
        if (radioSubnet.getSelection()) {
            InetAddress baseAddress = InetAddress.getByName(textAddr1.getText().trim());
            int maskBits = Integer.parseInt(textAddr2.getText().trim());
            if ((maskBits < 0) || ((baseAddress instanceof Inet4Address) && (maskBits > 32)) || ((baseAddress instanceof Inet6Address) && (maskBits > 128)))
                throw new NumberFormatException("Invalid network mask");
            element = new InetAddressListElement(baseAddress, maskBits);
        } else {
            element = new InetAddressListElement(InetAddress.getByName(textAddr1.getText().trim()), InetAddress.getByName(textAddr2.getText().trim()));
        }
    } catch (UnknownHostException e) {
        MessageDialogHelper.openWarning(getShell(), Messages.get().AddAddressListElementDialog_Warning, Messages.get().AddAddressListElementDialog_EnterValidData);
        return;
    } catch (NumberFormatException e) {
        MessageDialogHelper.openWarning(getShell(), Messages.get().AddAddressListElementDialog_Warning, Messages.get().AddAddressListElementDialog_EnterValidData);
        return;
    }
    super.okPressed();
}
Also used : InetAddressListElement(org.netxms.client.InetAddressListElement) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress)

Example 87 with Inet6Address

use of java.net.Inet6Address in project chromeview by pwnall.

the class AndroidNetworkLibrary method getNetworkList.

/**
 * @return the network interfaces list (if any) string. The items in
 *         the list string are delimited by a semicolon ";", each item
 *         is a network interface name and address pair and formatted
 *         as "name,address". e.g.
 *           eth0,10.0.0.2;eth0,fe80::5054:ff:fe12:3456
 *         represents a network list string which containts two items.
 */
@CalledByNative
public static String getNetworkList() {
    Enumeration<NetworkInterface> list = null;
    try {
        list = NetworkInterface.getNetworkInterfaces();
        if (list == null)
            return "";
    } catch (SocketException e) {
        Log.w(TAG, "Unable to get network interfaces: " + e);
        return "";
    }
    StringBuilder result = new StringBuilder();
    while (list.hasMoreElements()) {
        NetworkInterface netIf = list.nextElement();
        try {
            // Skip loopback interfaces, and ones which are down.
            if (!netIf.isUp() || netIf.isLoopback())
                continue;
            Enumeration<InetAddress> addressList = netIf.getInetAddresses();
            while (addressList.hasMoreElements()) {
                InetAddress address = addressList.nextElement();
                // Skip loopback addresses configured on non-loopback interfaces.
                if (address.isLoopbackAddress())
                    continue;
                StringBuilder addressString = new StringBuilder();
                addressString.append(netIf.getName());
                addressString.append(",");
                String ipAddress = address.getHostAddress();
                if (address instanceof Inet6Address && ipAddress.contains("%")) {
                    ipAddress = ipAddress.substring(0, ipAddress.lastIndexOf("%"));
                }
                addressString.append(ipAddress);
                if (result.length() != 0)
                    result.append(";");
                result.append(addressString.toString());
            }
        } catch (SocketException e) {
            continue;
        }
    }
    return result.toString();
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress) CalledByNative(org.chromium.base.CalledByNative)

Example 88 with Inet6Address

use of java.net.Inet6Address in project activemq-artemis by apache.

the class NettyConnector method createConnection.

@Override
public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }
    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()), ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }
    logger.debug("Remote destination: " + remoteDestination);
    ChannelFuture future;
    // port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }
    future.awaitUninterruptibly();
    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                // handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }
        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                // get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                String scheme = "http";
                if (sslEnabled) {
                    scheme = "https";
                }
                String ipv6Host = IPV6Util.encloseHost(host);
                URI uri = new URI(scheme, null, ipv6Host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
                request.headers().set(HttpHeaderNames.HOST, ipv6Host);
                request.headers().set(HttpHeaderNames.UPGRADE, ACTIVEMQ_REMOTING);
                request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.UPGRADE);
                final String serverName = ConfigurationHelper.getStringProperty(TransportConstants.ACTIVEMQ_SERVER_NAME, null, configuration);
                if (serverName != null) {
                    request.headers().set(TransportConstants.ACTIVEMQ_SERVER_NAME, serverName);
                }
                final String endpoint = ConfigurationHelper.getStringProperty(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }
                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);
                logger.debugf("Sending HTTP request %s", request);
                // Send the HTTP request.
                ch.writeAndFlush(request);
                if (!httpUpgradeHandler.awaitHandshake()) {
                    ch.close().awaitUninterruptibly();
                    return null;
                }
            } catch (URISyntaxException e) {
                ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
            channelHandler.active = true;
        }
        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, protocolManager);
        return conn;
    } else {
        Throwable t = future.cause();
        if (t != null && !(t instanceof ConnectException)) {
            ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }
        return null;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) BaseConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.BaseConnectionLifeCycleListener) ClientConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleListener) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) Channel(io.netty.channel.Channel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Inet6Address(java.net.Inet6Address) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) SslHandler(io.netty.handler.ssl.SslHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) ConnectException(java.net.ConnectException)

Example 89 with Inet6Address

use of java.net.Inet6Address in project vespa by vespa-engine.

the class DockerOperationsImpl method startContainer.

@Override
public void startContainer(ContainerName containerName, final ContainerNodeSpec nodeSpec) {
    PrefixLogger logger = PrefixLogger.getNodeAgentLogger(DockerOperationsImpl.class, containerName);
    logger.info("Starting container " + containerName);
    try {
        InetAddress nodeInetAddress = environment.getInetAddressForHost(nodeSpec.hostname);
        boolean isIPv6 = nodeInetAddress instanceof Inet6Address;
        if (isIPv6) {
            if (!docker.networkNPTed()) {
                docker.connectContainerToNetwork(containerName, "bridge");
            }
            docker.startContainer(containerName);
            setupContainerNetworkConnectivity(containerName);
        } else {
            docker.startContainer(containerName);
        }
        directoriesToMount.entrySet().stream().filter(Map.Entry::getValue).map(Map.Entry::getKey).forEach(path -> docker.executeInContainerAsRoot(containerName, "chmod", "-R", "a+w", path.toString()));
    } catch (IOException e) {
        throw new RuntimeException("Failed to start container " + containerName.asString(), e);
    }
}
Also used : Inet6Address(java.net.Inet6Address) IOException(java.io.IOException) InetAddress(java.net.InetAddress) HashMap(java.util.HashMap) Map(java.util.Map) PrefixLogger(com.yahoo.vespa.hosted.node.admin.util.PrefixLogger)

Example 90 with Inet6Address

use of java.net.Inet6Address in project vespa by vespa-engine.

the class DockerOperationsImpl method createContainer.

@Override
public void createContainer(ContainerName containerName, final ContainerNodeSpec nodeSpec) {
    PrefixLogger logger = PrefixLogger.getNodeAgentLogger(DockerOperationsImpl.class, containerName);
    logger.info("Creating container " + containerName);
    try {
        InetAddress nodeInetAddress = environment.getInetAddressForHost(nodeSpec.hostname);
        String configServers = environment.getConfigServerUris().stream().map(URI::getHost).collect(Collectors.joining(","));
        Docker.CreateContainerCommand command = docker.createContainerCommand(nodeSpec.wantedDockerImage.get(), ContainerResources.from(nodeSpec.minCpuCores, nodeSpec.minMainMemoryAvailableGb), containerName, nodeSpec.hostname).withManagedBy(MANAGER_NAME).withEnvironment("CONFIG_SERVER_ADDRESS", // TODO: Remove when all images support CONTAINER_ENVIRONMENT_SETTINGS
        configServers).withEnvironment("CONTAINER_ENVIRONMENT_SETTINGS", environment.getContainerEnvironmentResolver().createSettings(environment, nodeSpec)).withUlimit("nofile", 262_144, 262_144).withUlimit("nproc", 32_768, 409_600).withUlimit("core", -1, -1).withAddCapability(// Needed for gcore, pstack etc.
        "SYS_PTRACE").withAddCapability(// Needed for perf
        "SYS_ADMIN");
        if (environment.getNodeType() == NodeType.confighost || environment.getNodeType() == NodeType.proxyhost) {
            command.withVolume("/var/lib/sia", "/var/lib/sia");
        }
        if (environment.getNodeType() == NodeType.proxyhost) {
            command.withVolume("/opt/yahoo/share/ssl/certs/", "/opt/yahoo/share/ssl/certs/");
        }
        if (!docker.networkNPTed()) {
            command.withIpAddress(nodeInetAddress);
            command.withNetworkMode(DockerImpl.DOCKER_CUSTOM_MACVLAN_NETWORK_NAME);
            // TODO This is probably not necessary - review later
            command.withVolume("/etc/hosts", "/etc/hosts");
        } else {
            // IPv6 - Assume always valid
            Inet6Address ipV6Address = this.retriever.getIPv6Address(nodeSpec.hostname).orElseThrow(() -> new RuntimeException("Unable to find a valid IPv6 address. Missing an AAAA DNS entry?"));
            InetAddress ipV6Prefix = InetAddress.getByName(IPV6_NPT_PREFIX);
            InetAddress ipV6Local = IPAddresses.prefixTranslate(ipV6Address, ipV6Prefix, 8);
            command.withIpAddress(ipV6Local);
            // IPv4 - Only present for some containers
            Optional<Inet4Address> ipV4Address = this.retriever.getIPv4Address(nodeSpec.hostname);
            if (ipV4Address.isPresent()) {
                InetAddress ipV4Prefix = InetAddress.getByName(IPV4_NPT_PREFIX);
                InetAddress ipV4Local = IPAddresses.prefixTranslate(ipV4Address.get(), ipV4Prefix, 2);
                command.withIpAddress(ipV4Local);
            }
            command.withNetworkMode(DOCKER_CUSTOM_BRIDGE_NETWORK_NAME);
        }
        for (Path pathInNode : directoriesToMount.keySet()) {
            String pathInHost = environment.pathInHostFromPathInNode(containerName, pathInNode).toString();
            command.withVolume(pathInHost, pathInNode.toString());
        }
        // TODO: Enforce disk constraints
        long minMainMemoryAvailableMb = (long) (nodeSpec.minMainMemoryAvailableGb * 1024);
        if (minMainMemoryAvailableMb > 0) {
            // VESPA_TOTAL_MEMORY_MB is used to make any jdisc container think the machine
            // only has this much physical memory (overrides total memory reported by `free -m`).
            command.withEnvironment("VESPA_TOTAL_MEMORY_MB", Long.toString(minMainMemoryAvailableMb));
        }
        logger.info("Creating new container with args: " + command);
        command.create();
        docker.createContainer(command);
    } catch (IOException e) {
        throw new RuntimeException("Failed to create container " + containerName.asString(), e);
    }
}
Also used : Path(java.nio.file.Path) Inet4Address(java.net.Inet4Address) Docker(com.yahoo.vespa.hosted.dockerapi.Docker) Inet6Address(java.net.Inet6Address) IOException(java.io.IOException) InetAddress(java.net.InetAddress) PrefixLogger(com.yahoo.vespa.hosted.node.admin.util.PrefixLogger)

Aggregations

Inet6Address (java.net.Inet6Address)286 InetAddress (java.net.InetAddress)196 Inet4Address (java.net.Inet4Address)110 NetworkInterface (java.net.NetworkInterface)54 UnknownHostException (java.net.UnknownHostException)51 SocketException (java.net.SocketException)32 InetSocketAddress (java.net.InetSocketAddress)31 IOException (java.io.IOException)29 LinkAddress (android.net.LinkAddress)28 Test (org.junit.Test)26 RouteInfo (android.net.RouteInfo)21 IpPrefix (android.net.IpPrefix)19 ArrayList (java.util.ArrayList)19 LinkProperties (android.net.LinkProperties)15 ByteBuffer (java.nio.ByteBuffer)9 InterfaceAddress (java.net.InterfaceAddress)7 StringJoiner (java.util.StringJoiner)7 PrintWriter (java.io.PrintWriter)6 HashMap (java.util.HashMap)6 Test (org.junit.jupiter.api.Test)6