Example usage for java.net NetworkInterface getInetAddresses

List of usage examples for java.net NetworkInterface getInetAddresses

Introduction

In this page you can find the example usage for java.net NetworkInterface getInetAddresses.

Prototype

public Enumeration<InetAddress> getInetAddresses() 

Source Link

Document

Get an Enumeration with all or a subset of the InetAddresses bound to this network interface.

Usage

From source file:com.vuze.plugin.azVPN_PIA.Checker.java

/**
 * @return rebind sucessful, or rebinding to already bound address
 *//* www. j a  v a2  s . c  o m*/
private boolean rebindNetworkInterface(NetworkInterface networkInterface, InetAddress onlyToAddress,
        final StringBuilder sReply) {
    vpnIP = onlyToAddress;

    /**
    if (true) {
       sReply.append("Would rebind to " + networkInterface.getDisplayName()
       + onlyToAddress + "\n");
       return false;
    }
    /**/
    String ifName = networkInterface.getName();

    String configBindIP = config.getCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP);

    int bindNetworkInterfaceIndex = -1;
    if (onlyToAddress != null) {
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        for (int j = 0; inetAddresses.hasMoreElements(); j++) {
            InetAddress element = inetAddresses.nextElement();
            if (element.equals(onlyToAddress)) {
                bindNetworkInterfaceIndex = j;
                break;
            }
        }
    }

    if (configBindIP.equals(ifName) || (bindNetworkInterfaceIndex >= 0
            && configBindIP.equals(ifName + "[" + bindNetworkInterfaceIndex + "]"))) {

        addReply(sReply, CHAR_GOOD, "pia.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("PIA BindWait");

        NetworkAdmin.getSingleton().addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
            public void propertyChanged(String property) {
                if (property.equals(NetworkAdmin.PR_DEFAULT_BIND_ADDRESS)) {
                    sem.releaseForever();
                    NetworkAdmin.getSingleton().removePropertyChangeListener(this);

                    addReply(sReply, CHAR_GOOD, "pia.bind.complete.triggered");
                }
            }
        });

        // I think setting CORE_PARAM_STRING_LOCAL_BIND_IP is actually synchronous
        // We set up a PropertyChangeListener in case it ever becomes asynchronous
        config.setCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP, newConfigBindIP);
        config.setUnsafeBooleanParameter("Enforce Bind IP", true);
        config.setUnsafeBooleanParameter("Check Bind IP On Start", true);

        config.setUnsafeBooleanParameter("upnp.enable", false);
        config.setUnsafeBooleanParameter("natpmp.enable", false);

        addReply(sReply, CHAR_GOOD, "pia.change.binding", new String[] { "" + newConfigBindIP,
                networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

        sem.reserve(11000);
        return sem.isReleasedForever();
    }
    return true;
}

From source file:com.safi.asterisk.handler.SafletEngine.java

public List<String> getLocalIPAddresses() {
    List<String> iplist = new ArrayList<String>();
    NetworkInterface iface = null;
    try {/*  w  w  w.  ja v a  2s.c om*/
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements();) {
            iface = ifaces.nextElement();
            System.out.println("Interface:" + iface.getDisplayName());
            InetAddress ia = null;
            for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements();) {
                ia = ips.nextElement();
                if (Pattern.matches(AbstractConnectionManager.PATTERN_IP, ia.getHostAddress())) {
                    iplist.add(ia.getHostAddress());
                }
            }
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return iplist;
}

From source file:com.stimulus.archiva.presentation.ConfigBean.java

protected void addIpAddresses(ArrayList<String> ipAddresses) {
    try {//w ww. ja va 2 s  .  co  m
        for (Enumeration e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) e.nextElement();
            for (Enumeration a = iface.getInetAddresses(); a.hasMoreElements();) {
                InetAddress addr = (InetAddress) a.nextElement();
                ipAddresses.add(addr.getHostAddress());
            }
        }
    } catch (Exception e) {
        logger.error("failed to retrieve bind ip addresses:" + e.getMessage());
    }
}

From source file:com.httrack.android.HTTrackActivity.java

/**
 * Return the IPv6 address./*w  ww.jav  a 2s  .c  om*/
 * 
 * @return The ipv6 address, or @c null if no IPv6 connectivity is available.
 */
protected static InetAddress getIPv6Address() {
    try {
        for (final Enumeration<NetworkInterface> interfaces = NetworkInterface
                .getNetworkInterfaces(); interfaces.hasMoreElements();) {
            final NetworkInterface iface = interfaces.nextElement();
            for (final Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses
                    .hasMoreElements();) {
                final InetAddress address = addresses.nextElement();
                Log.d(HTTrackActivity.class.getSimpleName(), "seen interface: " + address.toString());
                if (address instanceof Inet6Address) {
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()
                            && !address.isSiteLocalAddress() && !address.isMulticastAddress()) {
                        return address;
                    }
                }
            }
        }
    } catch (final SocketException se) {
        Log.w(HTTrackActivity.class.getSimpleName(), "could not enumerate interfaces", se);
    }
    return null;
}

From source file:org.apache.nifi.web.server.JettyServer.java

private void configureConnectors(final Server server) throws ServerConfigurationException {
    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setRequestHeaderSize(HEADER_BUFFER_SIZE);
    httpConfiguration.setResponseHeaderSize(HEADER_BUFFER_SIZE);

    if (props.getPort() != null) {
        final Integer port = props.getPort();
        if (port < 0 || (int) Math.pow(2, 16) <= port) {
            throw new ServerConfigurationException("Invalid HTTP port: " + port);
        }// ww w.j  av  a  2  s .c o m

        logger.info("Configuring Jetty for HTTP on port: " + port);

        final List<Connector> serverConnectors = Lists.newArrayList();

        final Map<String, String> httpNetworkInterfaces = props.getHttpNetworkInterfaces();
        if (httpNetworkInterfaces.isEmpty() || httpNetworkInterfaces.values().stream()
                .filter(value -> !Strings.isNullOrEmpty(value)).collect(Collectors.toList()).isEmpty()) {
            // create the connector
            final ServerConnector http = new ServerConnector(server,
                    new HttpConnectionFactory(httpConfiguration));
            // set host and port
            if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.WEB_HTTP_HOST))) {
                http.setHost(props.getProperty(NiFiProperties.WEB_HTTP_HOST));
            }
            http.setPort(port);
            serverConnectors.add(http);
        } else {
            // add connectors for all IPs from http network interfaces
            serverConnectors
                    .addAll(Lists.newArrayList(httpNetworkInterfaces.values().stream().map(ifaceName -> {
                        NetworkInterface iface = null;
                        try {
                            iface = NetworkInterface.getByName(ifaceName);
                        } catch (SocketException e) {
                            logger.error("Unable to get network interface by name {}", ifaceName, e);
                        }
                        if (iface == null) {
                            logger.warn("Unable to find network interface named {}", ifaceName);
                        }
                        return iface;
                    }).filter(Objects::nonNull)
                            .flatMap(iface -> Collections.list(iface.getInetAddresses()).stream())
                            .map(inetAddress -> {
                                // create the connector
                                final ServerConnector http = new ServerConnector(server,
                                        new HttpConnectionFactory(httpConfiguration));
                                // set host and port
                                http.setHost(inetAddress.getHostAddress());
                                http.setPort(port);
                                return http;
                            }).collect(Collectors.toList())));
        }
        // add all connectors
        serverConnectors.forEach(server::addConnector);
    }

    if (props.getSslPort() != null) {
        final Integer port = props.getSslPort();
        if (port < 0 || (int) Math.pow(2, 16) <= port) {
            throw new ServerConfigurationException("Invalid HTTPs port: " + port);
        }

        logger.info("Configuring Jetty for HTTPs on port: " + port);

        final List<Connector> serverConnectors = Lists.newArrayList();

        final Map<String, String> httpsNetworkInterfaces = props.getHttpsNetworkInterfaces();
        if (httpsNetworkInterfaces.isEmpty() || httpsNetworkInterfaces.values().stream()
                .filter(value -> !Strings.isNullOrEmpty(value)).collect(Collectors.toList()).isEmpty()) {
            final ServerConnector https = createUnconfiguredSslServerConnector(server, httpConfiguration);

            // set host and port
            if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.WEB_HTTPS_HOST))) {
                https.setHost(props.getProperty(NiFiProperties.WEB_HTTPS_HOST));
            }
            https.setPort(port);
            serverConnectors.add(https);
        } else {
            // add connectors for all IPs from https network interfaces
            serverConnectors
                    .addAll(Lists.newArrayList(httpsNetworkInterfaces.values().stream().map(ifaceName -> {
                        NetworkInterface iface = null;
                        try {
                            iface = NetworkInterface.getByName(ifaceName);
                        } catch (SocketException e) {
                            logger.error("Unable to get network interface by name {}", ifaceName, e);
                        }
                        if (iface == null) {
                            logger.warn("Unable to find network interface named {}", ifaceName);
                        }
                        return iface;
                    }).filter(Objects::nonNull)
                            .flatMap(iface -> Collections.list(iface.getInetAddresses()).stream())
                            .map(inetAddress -> {
                                final ServerConnector https = createUnconfiguredSslServerConnector(server,
                                        httpConfiguration);

                                // set host and port
                                https.setHost(inetAddress.getHostAddress());
                                https.setPort(port);
                                return https;
                            }).collect(Collectors.toList())));
        }
        // add all connectors
        serverConnectors.forEach(server::addConnector);
    }
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ?IP?.//from  www .j a  v  a2  s  . c o  m
 * 
 * @return ?IP
 */
public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {

                    String ipAddr = inetAddress.getHostAddress();
                    return ipAddr;
                }
            }
        }
    } catch (Exception e) {
        if (BuildConfig.DEBUG) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.vuze.plugin.azVPN_Air.Checker.java

/**
 * @return rebind sucessful, or rebinding to already bound address
 *//*from  w ww  .  j  a  va 2  s.  c o  m*/
private boolean rebindNetworkInterface(NetworkInterface networkInterface, InetAddress onlyToAddress,
        final StringBuilder sReply) {
    vpnIP = onlyToAddress;

    /**
    if (true) {
       sReply.append("Would rebind to " + networkInterface.getDisplayName()
       + onlyToAddress + "\n");
       return false;
    }
    /**/
    String ifName = networkInterface.getName();

    String configBindIP = config.getCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP);

    int bindNetworkInterfaceIndex = -1;
    if (onlyToAddress != null) {
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        for (int j = 0; inetAddresses.hasMoreElements(); j++) {
            InetAddress element = inetAddresses.nextElement();
            if (element.equals(onlyToAddress)) {
                bindNetworkInterfaceIndex = j;
                break;
            }
        }
    }

    if (configBindIP.equals(ifName) || (bindNetworkInterfaceIndex >= 0
            && configBindIP.equals(ifName + "[" + bindNetworkInterfaceIndex + "]"))) {

        addReply(sReply, CHAR_GOOD, "airvpn.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("AirVPN BindWait");

        NetworkAdmin.getSingleton().addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
            public void propertyChanged(String property) {
                if (property.equals(NetworkAdmin.PR_DEFAULT_BIND_ADDRESS)) {
                    sem.releaseForever();
                    NetworkAdmin.getSingleton().removePropertyChangeListener(this);

                    addReply(sReply, CHAR_GOOD, "airvpn.bind.complete.triggered");
                }
            }
        });

        // I think setting CORE_PARAM_STRING_LOCAL_BIND_IP is actually synchronous
        // We set up a PropertyChangeListener in case it ever becomes asynchronous
        config.setCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP, newConfigBindIP);
        config.setUnsafeBooleanParameter("Enforce Bind IP", true);
        config.setUnsafeBooleanParameter("Check Bind IP On Start", true);

        config.setUnsafeBooleanParameter("upnp.enable", false);
        config.setUnsafeBooleanParameter("natpmp.enable", false);

        addReply(sReply, CHAR_GOOD, "airvpn.change.binding", new String[] { "" + newConfigBindIP,
                networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

        sem.reserve(11000);
        return sem.isReleasedForever();
    }
    return true;
}

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

/**
 * @return rebind sucessful, or rebinding to already bound address
 *///from w ww .j  av  a2 s .c  o m
private final boolean rebindNetworkInterface(NetworkInterface networkInterface, InetAddress onlyToAddress,
        final StringBuilder sReply) {
    vpnIP = onlyToAddress;

    config.setUnsafeBooleanParameter("Enforce Bind IP", true);
    config.setUnsafeBooleanParameter("Check Bind IP On Start", true);
    config.setUnsafeBooleanParameter("Plugin.UPnP.upnp.enable", false);
    config.setUnsafeBooleanParameter("Plugin.UPnP.natpmp.enable", false);

    /**
    if (true) {
       sReply.append("Would rebind to " + networkInterface.getDisplayName()
       + onlyToAddress + "\n");
       return false;
    }
    /**/

    String ifName = networkInterface.getName();

    String configBindIP = config.getCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP);

    int bindNetworkInterfaceIndex = -1;
    if (onlyToAddress != null) {
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        for (int j = 0; inetAddresses.hasMoreElements(); j++) {
            InetAddress element = inetAddresses.nextElement();
            if (element.equals(onlyToAddress)) {
                bindNetworkInterfaceIndex = j;
                break;
            }
        }
    }

    if (configBindIP.equals(ifName) || (bindNetworkInterfaceIndex >= 0
            && configBindIP.equals(ifName + "[" + bindNetworkInterfaceIndex + "]"))) {

        addReply(sReply, CHAR_GOOD, "vpnhelper.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("VPNHelper BindWait");

        NetworkAdmin.getSingleton().addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
            public void propertyChanged(String property) {
                if (property.equals(NetworkAdmin.PR_DEFAULT_BIND_ADDRESS)) {
                    sem.releaseForever();
                    NetworkAdmin.getSingleton().removePropertyChangeListener(this);

                    addReply(sReply, CHAR_GOOD, "vpnhelper.bind.complete.triggered");
                }
            }
        });

        // I think setting CORE_PARAM_STRING_LOCAL_BIND_IP is actually synchronous
        // We set up a PropertyChangeListener in case it ever becomes asynchronous
        config.setCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP, newConfigBindIP);

        addReply(sReply, CHAR_GOOD, "vpnhelper.change.binding",
                new String[] { "" + newConfigBindIP, networkInterface == null ? "null"
                        : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

        sem.reserve(11000);
        return sem.isReleasedForever();
    }
    return true;
}

From source file:com.adito.server.DefaultAditoServerFactory.java

private void displaySystemInfo() throws SocketException {

    if (useDevConfig) {
        LOG.warn("Development environment enabled. Do not use this on a production server.");
    }/*from w w  w. j  a v  a 2  s. c o m*/

    if (LOG.isInfoEnabled()) {
        LOG.info("Version is " + ContextHolder.getContext().getVersion());
        LOG.info("Java version is " + SystemProperties.get("java.version"));
        LOG.info("Server is installed on " + hostname + "/" + hostAddress);
        LOG.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("Adito does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        LOG.warn("********** WARNING **********");
        LOG.warn("The system has detected that the Java runtime is GNU/GCJ");
        LOG.warn("Adito may not work correctly with this Java runtime");
        LOG.warn("you should reconfigure with a different runtime");
        LOG.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (LOG.isInfoEnabled()) {
            LOG.info("Net interface: " + netface.getName());
        }

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (LOG.isInfoEnabled()) {
                LOG.info("IP address: " + ip.toString());
            }
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("System properties follow:");
    }
    Properties sysProps = System.getProperties();
    for (Map.Entry entry : sysProps.entrySet()) {
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("java.class.path=" + s);
                    }
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    }
                    idx += 256;
                } else {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx));
                    }
                    break;
                }
            }
        }
    }
}

From source file:com.adito.server.Main.java

private void displaySystemInfo() throws SocketException {

    ////  w  ww.  ja  va2 s .c  o  m

    if (useDevConfig) {
        log.warn("Development environment enabled. Do not use this on a production server.");
    }

    if (log.isInfoEnabled()) {
        log.info("Version is " + ContextHolder.getContext().getVersion());
        log.info("Java version is " + SystemProperties.get("java.version"));
        log.info("Server is installed on " + hostname + "/" + hostAddress);
        log.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("Adito does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        log.warn("********** WARNING **********");
        log.warn("The system has detected that the Java runtime is GNU/GCJ");
        log.warn("Adito may not work correctly with this Java runtime");
        log.warn("you should reconfigure with a different runtime");
        log.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (log.isInfoEnabled())
            log.info("Net interface: " + netface.getName());

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (log.isInfoEnabled())
                log.info("IP address: " + ip.toString());
        }
    }

    if (log.isInfoEnabled())
        log.info("System properties follow:");
    Properties sysProps = System.getProperties();
    for (Iterator i = sysProps.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (log.isInfoEnabled())
                        log.info("java.class.path=" + s);
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    idx += 256;
                } else {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx));
                    break;
                }
            }
        }
    }
}