Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

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

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:ru.asmsoft.p2p.incoming.LocalAddressesFilteringService.java

@PostConstruct
public void init() {
    try {//from   w ww . j  av  a 2  s.co  m
        logger.info("Full list of Network Interfaces:");
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            logger.info("    " + intf.getName() + " " + intf.getDisplayName());
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                String ip = enumIpAddr.nextElement().toString().replace("/", "");
                logger.info("        " + ip);
                localIpAddresses.add(ip);
            }
        }
    } catch (SocketException e) {
        logger.info(" (error retrieving network interface list)");
    }
}

From source file:com.ephesoft.dcma.util.NetworkUtil.java

/**
 * Utility method which will fetch the ip address of the system.
 * /*from  w  w w  .  jav  a2  s. com*/
 * @return ip address of the system.
 */
public static String getSystemIPAddress() {

    StringBuilder input = new StringBuilder(UtilConstants.INPUT_CONST);
    boolean first = true;
    String returnAddress = null;
    try {
        for (Enumeration<NetworkInterface> enumer = NetworkInterface.getNetworkInterfaces(); enumer
                .hasMoreElements();) {
            NetworkInterface netInterface = enumer.nextElement();
            Enumeration<InetAddress> inetEnum = netInterface.getInetAddresses();
            while (inetEnum.hasMoreElements()) {
                InetAddress inetAddress = inetEnum.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    if (first) {
                        first = false;
                    } else {
                        input.append(UtilConstants.FORWARD_SLASH);
                    }
                    input.append(inetAddress.getHostAddress());
                }
            }
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        returnAddress = IPADDRESS;
    }
    if (null == returnAddress) {
        returnAddress = first ? IPADDRESS : input.toString();
    }
    return returnAddress;
}

From source file:eu.betaas.betaasandroidapp.configuration.Configuration.java

private void setDeviceIp() {
    try {//from  w w  w .ja  va  2 s  .c om
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (isIPv4) {
                        deviceIP = sAddr;
                    }
                }
            }
        }
    } catch (Exception ex) {
        deviceIP = null;
    }
}

From source file:com.jaeksoft.searchlib.util.NetworksUtils.java

public static final String getFirstHardwareAddress()
        throws URISyntaxException, UnknownHostException, SocketException {
    InetAddress localhost = InetAddress.getLocalHost();
    String hardwareAddress = null;
    if (localhost != null)
        hardwareAddress = getHardwareAddress(NetworkInterface.getByInetAddress(localhost));
    if (hardwareAddress != null)
        return hardwareAddress;
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        hardwareAddress = getHardwareAddress(networkInterfaces.nextElement());
        if (hardwareAddress != null)
            return hardwareAddress;
    }/*from  w  w  w.  j  a v a2s .  c  om*/
    return null;
}

From source file:org.openhab.binding.vera.internal.discovery.VeraBridgeDiscoveryService.java

private void scan() {
    logger.debug("Starting scan for Vera controller");

    ValidateIPV4 validator = new ValidateIPV4();

    try {//from   w w w . j  a  va  2s . co m
        Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterface.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterface.nextElement();
            if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) {
                for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
                    if (validator.isValidIPV4(address.getAddress().getHostAddress())) {
                        String ipAddress = address.getAddress().getHostAddress();
                        Short prefix = address.getNetworkPrefixLength();

                        logger.debug("Scan IP address for Vera Controller: {}", ipAddress);

                        String subnet = ipAddress + "/" + prefix;
                        SubnetUtils utils = new SubnetUtils(subnet);
                        String[] addresses = utils.getInfo().getAllAddresses();

                        for (String addressInSubnet : addresses) {
                            scheduler.execute(new VeraControllerScan(addressInSubnet));
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        logger.warn("Error occurred while searching Vera controller: ", e);
    }
}

From source file:org.apache.carbondata.core.dictionary.service.AbstractDictionaryServer.java

public String findLocalIpAddress(Logger LOGGER) {
    try {//from  w  ww .  ja  v a2 s.  c om
        String defaultIpOverride = System.getenv("SPARK_LOCAL_IP");
        if (defaultIpOverride != null) {
            return defaultIpOverride;
        } else {
            InetAddress address = InetAddress.getLocalHost();
            if (address.isLoopbackAddress()) {
                // Address resolves to something like 127.0.1.1, which happens on Debian; try to find
                // a better address using the local network interfaces
                // getNetworkInterfaces returns ifs in reverse order compared to ifconfig output order
                // on unix-like system. On windows, it returns in index order.
                // It's more proper to pick ip address following system output order.
                Enumeration<NetworkInterface> activeNetworkIFs = NetworkInterface.getNetworkInterfaces();
                List<NetworkInterface> reOrderedNetworkIFs = new ArrayList<NetworkInterface>();
                while (activeNetworkIFs.hasMoreElements()) {
                    reOrderedNetworkIFs.add(activeNetworkIFs.nextElement());
                }

                if (!SystemUtils.IS_OS_WINDOWS) {
                    Collections.reverse(reOrderedNetworkIFs);
                }

                for (NetworkInterface ni : reOrderedNetworkIFs) {
                    Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress addr = inetAddresses.nextElement();
                        if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
                                && addr instanceof Inet4Address) {
                            // We've found an address that looks reasonable!
                            LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                                    + " resolves to a loopback address: " + address.getHostAddress()
                                    + "; using " + addr.getHostAddress() + " instead (on interface "
                                    + ni.getName() + ")");
                            LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                            return addr.getHostAddress();
                        }
                    }
                    LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                            + " resolves to a loopback address: " + address.getHostAddress()
                            + ", but we couldn't find any external IP address!");
                    LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                }
            }
            return address.getHostAddress();
        }
    } catch (UnknownHostException e) {
        LOGGER.error("do not get local host address:" + e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (SocketException e) {
        LOGGER.error("do not get net work interface:" + e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:license.mac.MacTest.java

/**
 * mac?/*from w  ww . j  a v  a2  s.  c o m*/
 * @return
 * @throws SocketException
 */
public boolean checkMac() throws SocketException {
    StringBuffer sb = new StringBuffer();
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    int i = 12;
    Base64 base64 = new Base64();
    for (NetworkInterface ni : Collections.list(interfaces)) {
        if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
            sb.append(String.valueOf(i)).append('=').append(ni.getName()).append('\n');
            i++;
            byte[] mac = ni.getHardwareAddress();
            sb.append(String.valueOf(i)).append('=').append(base64.encodeAsString(mac)).append('\n');
            i++;
        }
    }
    System.out.println(sb.toString());
    return true;
}

From source file:com.netsteadfast.greenstep.util.HostUtils.java

public static String getHostAddress() {
    String hostAddress = "";
    try {//from   w w  w  . j a  va  2 s. com
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
        for (; nics.hasMoreElements() && "".equals(hostAddress);) {
            NetworkInterface interfece = nics.nextElement();
            if (interfece.getName().toLowerCase().startsWith("lo")) {
                continue;
            }
            Enumeration<InetAddress> addrs = interfece.getInetAddresses();
            for (; addrs.hasMoreElements() && "".equals(hostAddress);) {
                InetAddress addr = addrs.nextElement();
                if (addr.getHostAddress().indexOf(":") > -1) {
                    continue;
                }
                hostAddress = addr.getHostAddress();
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    if (StringUtils.isBlank(hostAddress)) {
        hostAddress = "127.0.0.1";
    }
    return hostAddress;
}

From source file:org.trafodion.rest.util.NetworkConfiguration.java

public NetworkConfiguration(Configuration conf) throws Exception {

    this.conf = conf;
    ia = InetAddress.getLocalHost();

    String dnsInterface = conf.get(Constants.REST_DNS_INTERFACE, Constants.DEFAULT_REST_DNS_INTERFACE);
    if (dnsInterface.equalsIgnoreCase("default")) {
        intHostAddress = extHostAddress = ia.getHostAddress();
        canonicalHostName = ia.getCanonicalHostName();
        LOG.info("Using local host [" + canonicalHostName + "," + extHostAddress + "]");
    } else {//  w w w. j  ava  2 s .  c om
        // For all nics get all hostnames and addresses   
        // and try to match against rest.dns.interface property 
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
        while (nics.hasMoreElements() && !matchedInterface) {
            InetAddress inet = null;
            NetworkInterface ni = nics.nextElement();
            LOG.info("Found interface [" + ni.getDisplayName() + "]");
            if (dnsInterface.equalsIgnoreCase(ni.getDisplayName())) {
                LOG.info("Matched specified interface [" + ni.getName() + "]");
                inet = getInetAddress(ni);
                getCanonicalHostName(ni, inet);
            } else {
                Enumeration<NetworkInterface> subIfs = ni.getSubInterfaces();
                for (NetworkInterface subIf : Collections.list(subIfs)) {
                    LOG.debug("Sub Interface Display name [" + subIf.getDisplayName() + "]");
                    if (dnsInterface.equalsIgnoreCase(subIf.getDisplayName())) {
                        LOG.info("Matched subIf [" + subIf.getName() + "]");
                        inet = getInetAddress(subIf);
                        getCanonicalHostName(subIf, inet);
                        break;
                    }
                }
            }
        }
    }

    if (!matchedInterface)
        checkCloud();
}

From source file:com.orangelabs.rcs.platform.network.AndroidNetworkFactory.java

/**
 * Returns the local IP address of a given network interface
 * /* ww w  .  j av  a2s.c o  m*/
 * @param dnsEntry remote address to find an according local socket address
  * @param type the type of the network interface, should be either
  *        {@link android.net.ConnectivityManager#TYPE_WIFI} or {@link android.net.ConnectivityManager#TYPE_MOBILE}
 * @return Address
 */
// Changed by Deutsche Telekom
public String getLocalIpAddress(DnsResolvedFields dnsEntry, int type) {
    String ipAddress = null;
    try {
        // What kind of remote address (P-CSCF) are we trying to reach?
        boolean isIpv4 = InetAddressUtils.isIPv4Address(dnsEntry.ipAddress);

        // check all available interfaces
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); (en != null)
                && en.hasMoreElements();) {
            NetworkInterface netIntf = (NetworkInterface) en.nextElement();
            for (Enumeration<InetAddress> addr = netIntf.getInetAddresses(); addr.hasMoreElements();) {
                InetAddress inetAddress = addr.nextElement();
                ipAddress = IpAddressUtils.extractHostAddress(inetAddress.getHostAddress());
                // if IP address version doesn't match to remote address
                // version then skip
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                        && (InetAddressUtils.isIPv4Address(ipAddress) == isIpv4)) {
                    String intfName = netIntf.getDisplayName().toLowerCase();
                    // some devices do list several interfaces though only
                    // one is active
                    if (((type == ConnectivityManager.TYPE_WIFI) && intfName.startsWith("wlan"))
                            || ((type == ConnectivityManager.TYPE_MOBILE) && !intfName.startsWith("wlan"))) {
                        return ipAddress;
                    }
                }
            }
        }
    } catch (Exception e) {
        if (logger.isActivated()) {
            logger.error("getLocalIpAddress failed with ", e);
        }
    }
    return ipAddress;
}