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:net.grinder.util.NetworkUtil.java

private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
        throws SocketException {
    Enumeration<?> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        if (!i.isUp()) {
            continue;
        }//from   ww  w. j  ava  2  s .  co  m
        for (Enumeration<?> en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}

From source file:de.pawlidi.openaletheia.utils.AletheiaUtils.java

/**
 * // w w w . jav a2  s .  co m
 * @return
 * @throws UnknownHostException
 */
public static InetAddress getLocalIpAddress() throws UnknownHostException {
    try {
        InetAddress localAddress = null;
        // load all existed network interfaces
        for (Enumeration<?> networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces
                .hasMoreElements();) {
            NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();

            for (Enumeration<?> ipAddresses = networkInterface.getInetAddresses(); ipAddresses
                    .hasMoreElements();) {
                InetAddress ipAddress = (InetAddress) ipAddresses.nextElement();
                if (!ipAddress.isLoopbackAddress()) {
                    if (ipAddress.isSiteLocalAddress()) {
                        return ipAddress;
                    } else if (localAddress == null) {
                        localAddress = ipAddress;
                    }
                }
            }
        }
        if (localAddress != null) {
            return localAddress;
        }
        // try to get localhost address
        localAddress = InetAddress.getLocalHost();
        if (localAddress == null) {
            throw new UnknownHostException("Could not load localhost ip address");
        }
        return localAddress;
    } catch (Exception e) {
        UnknownHostException unknownHostException = new UnknownHostException(
                "Could not load localhost ip address " + e);
        unknownHostException.initCause(e);
        throw unknownHostException;
    }
}

From source file:otsopack.commons.network.coordination.spacemanager.HttpSpaceManager.java

public static String getIpAddress() {
    try {//from w  ww . j av  a2 s . c  om
        final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netIf : Collections.list(nets)) {
            // If the network is active
            if (isUp(netIf)) {
                Enumeration<InetAddress> addresses = netIf.getInetAddresses();
                for (InetAddress addr : Collections.list(addresses))
                    // If the IP address is IPv4 and it's not the local address, store it
                    if (addr.getAddress().length == 4 && !addr.isLoopbackAddress())
                        return addr.getHostAddress();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:cycronix.CTandroid.CTAserver.java

/**
 * Get IP address from first non-localhost interface
 * @param ipv4  true=return ipv4, false=return ipv6
 * @return  address or empty string/*from w w w  .  ja v a2 s.co m*/
 */
public static String getIPAddress(boolean useIPv4) {
    try {
        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();
                    // org.apache.http.conn.util is no longer supported under Android API 23
                    // http://stackoverflow.com/questions/32141785/android-api-23-inetaddressutils-replacement
                    // https://developer.android.com/sdk/api_diff/23/changes.html
                    // boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    InetAddress tempInetAddress = InetAddress.getByName(sAddr);
                    boolean isIPv4 = false;
                    if (tempInetAddress instanceof Inet4Address) {
                        isIPv4 = true;
                    }
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "Unknown";
}

From source file:com.starit.diamond.client.processor.LocalConfigInfoProcessor.java

static String getHostAddress() {
    String address = "127.0.0.1";
    try {/*from w  w  w .  j  a  v a2s .  c om*/
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface ni = en.nextElement();
            Enumeration<InetAddress> ads = ni.getInetAddresses();
            while (ads.hasMoreElements()) {
                InetAddress ip = ads.nextElement();
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    return ip.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("??", e);
    }
    return address;
}

From source file:com.vaadin.tests.tb3.PrivateTB3Configuration.java

/**
 * Tries to automatically determine the IP address of the machine the test
 * is running on.// ww  w  .  j a v  a 2s .  c  o m
 * 
 * @return An IP address of one of the network interfaces in the machine.
 * @throws RuntimeException
 *             if there was an error or no IP was found
 */
private static String findAutoHostname() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface nwInterface = interfaces.nextElement();
            if (!nwInterface.isUp() || nwInterface.isLoopback() || nwInterface.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = nwInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address.isLoopbackAddress()) {
                    continue;
                }
                if (address.isSiteLocalAddress()) {
                    return address.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("Could not enumerate ");
    }

    throw new RuntimeException("No compatible (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) ip address found.");
}

From source file:org.magnum.dataup.VideoController.java

private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
    try {/* ww w  .  j a  v  a2  s.c o  m*/
        InetAddress candidateAddress = null;
        // Iterate all NICs (network interface cards)...
        for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {

                    if (inetAddr.isSiteLocalAddress()) {
                        // Found non-loopback site-local address. Return it immediately...
                        return inetAddr;
                    } else if (candidateAddress == null) {
                        // Found non-loopback address, but not necessarily site-local.
                        // Store it as a candidate to be returned if site-local address is not subsequently found...
                        candidateAddress = inetAddr;
                        // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
                        // only the first. For subsequent iterations, candidate will be non-null.
                    }
                }
            }
        }
        if (candidateAddress != null) {
            // We did not find a site-local address, but we found some other non-loopback address.
            // Server might have a non-site-local address assigned to its NIC (or it might be running
            // IPv6 which deprecates the "site-local" concept).
            // Return this non-loopback candidate address...
            return candidateAddress;
        }
        // At this point, we did not find a non-loopback address.
        // Fall back to returning whatever InetAddress.getLocalHost() returns...
        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress == null) {
            throw new UnknownHostException(
                    "The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
        }
        return jdkSuppliedAddress;
    } catch (Exception e) {
        UnknownHostException unknownHostException = new UnknownHostException(
                "Failed to determine LAN address: " + e);
        unknownHostException.initCause(e);
        throw unknownHostException;
    }
}

From source file:org.apache.synapse.transport.passthru.util.PassThroughTransportUtils.java

/**
 * Whatever this method returns as the IP is ignored by the actual http/s listener when
 * its getServiceEPR is invoked. This was originally copied from axis2
 *
 * @return Returns String.//from  www  .j a va2 s. c  om
 * @throws java.net.SocketException if the socket can not be accessed
 */
public static String getIpAddress() throws SocketException {
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    String address = "127.0.0.1";

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        Enumeration addresses = netface.getInetAddresses();

        while (addresses.hasMoreElements()) {
            InetAddress ip = (InetAddress) addresses.nextElement();
            if (!ip.isLoopbackAddress() && isIP(ip.getHostAddress())) {
                return ip.getHostAddress();
            }
        }
    }
    return address;
}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

public static String getLocalIP(boolean useIPv4) {
    String ip = "No Local IP assigned";
    try {/*  w  w  w. j a  va  2s.  c  o m*/

        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ni : interfaces) {
            List<InetAddress> addresses = Collections.list(ni.getInetAddresses());
            for (InetAddress ia : addresses) {
                if (ia != null && !ia.isLoopbackAddress()) {
                    String sAddr = ia.getHostAddress().toUpperCase(Locale.ENGLISH);
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4) {
                            ip = sAddr;
                        }
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%');
                            ip = delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        ip = "Unknown Error, Report it!";
    }
    return ip;
}

From source file:com.triggertrap.ZeroConf.java

/**
 * Returns the first found IP4 address./*from w w  w.  j  av  a  2s .c  o  m*/
 * 
 * @return the first found IP4 address
 */
public static InetAddress getIPAddress(int wifi_ipaddr) {
    try {
        String ipString = String.format("%d.%d.%d.%d", (wifi_ipaddr & 0xff), (wifi_ipaddr >> 8 & 0xff),
                (wifi_ipaddr >> 16 & 0xff), (wifi_ipaddr >> 24 & 0xff));

        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() && (ipString.equals(addr.getHostAddress()))) {
                    //String sAddr = addr.getHostAddress().toUpperCase();
                    if (addr instanceof java.net.Inet4Address) {
                        //Log.d("found IP address to listen: " , sAddr);
                        return addr;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}