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:edu.usc.pgroup.floe.utils.Utils.java

/**
 * returns the canonical host name. This assumes a unique host name for
 * each machine in the cluster does not apply.
 * FixMe: In local cloud environment (local eucalyptus in system mode)
 * where the DNS server is not running, this might be an issue.
 * @return The first IPv4 address found for any interface that is up and
 * running.//from   w  w w .  j  av a 2s  .  co m
 */
public static String getIpAddress() {
    String ip = null;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        LOGGER.error("Getting ip");

        while (interfaces.hasMoreElements()) {
            LOGGER.error("Next iface");
            NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress currentAddr = addresses.nextElement();
                if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
                    continue;
                }
                ip = currentAddr.getHostAddress();
            }
        }
    } catch (SocketException e) {
        LOGGER.error("Error occurred while retrieving hostname" + e.getMessage());
        throw new RuntimeException("Error occurred while " + "retrieving hostname" + e.getMessage());
    }
    return ip;
}

From source file:org.brandroid.openmanager.fragments.DialogHandler.java

private static String getNetworkInterfaces() {
    String ret = "IP Address:";
    try {/* w  w  w .j  a  v  a  2  s.c o  m*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface ni = en.nextElement();
            for (Enumeration<InetAddress> enumIP = ni.getInetAddresses(); enumIP.hasMoreElements();) {
                InetAddress ip = enumIP.nextElement();
                if (!ip.isLoopbackAddress())
                    ret += " " + ip.getHostAddress();
            }
        }
    } catch (SocketException e) {
        Logger.LogError("Couldn't get Network Interfaces", e);
    }
    ret += "\n";
    return ret;
}

From source file:com.git.original.common.utils.IPUtils.java

/**
 * ?IP?/*from  w w w  . j  a v a2 s  .  c  om*/
 * <p>
 * :<br/>
 * 1. 220.xxx.xxx.xxx<br>
 * 2. 123.xxx.xxx.xxx<br>
 * other<br>
 * 
 * @return
 * @throws SocketException
 *             If an I/O error occurs.
 * @throws NullPointerException
 *             can not found the interface
 * @throws RuntimeException
 *             can not get net address
 */
public static InetAddress getWANIpv4Address(String interfaceName)
        throws SocketException, NullPointerException, RuntimeException {

    InetAddress ipStartWith123 = null;
    InetAddress ipv4Addr = null;

    if (StringUtils.isNotEmpty(interfaceName)) {
        // ?
        NetworkInterface netInterface = NetworkInterface.getByName(interfaceName.trim());
        if (netInterface == null) {
            throw new NullPointerException("can not found the network interface by name: " + interfaceName);
        }

        Enumeration<InetAddress> addrEnum = netInterface.getInetAddresses();
        while (addrEnum.hasMoreElements()) {
            InetAddress addr = addrEnum.nextElement();
            String hostAddr = addr.getHostAddress();

            if (hostAddr.startsWith("220.")) {
                return addr;
            } else if (ipStartWith123 == null && hostAddr.startsWith("123.")) {
                ipStartWith123 = addr;
            } else if (addr instanceof Inet4Address) {
                ipv4Addr = addr;
            }
        }
    } else {
        /*
         * ???
         */
        Enumeration<NetworkInterface> interfaceEnum = NetworkInterface.getNetworkInterfaces();
        while (interfaceEnum.hasMoreElements()) {
            NetworkInterface netInterface = interfaceEnum.nextElement();
            if (netInterface.isLoopback() || !netInterface.isUp()) {
                continue;
            }

            Enumeration<InetAddress> addrEnum = netInterface.getInetAddresses();
            while (addrEnum.hasMoreElements()) {
                InetAddress addr = addrEnum.nextElement();
                String hostAddr = addr.getHostAddress();

                if (hostAddr.startsWith("220.")) {
                    return addr;
                } else if (ipStartWith123 == null && hostAddr.startsWith("123.")) {
                    ipStartWith123 = addr;
                } else if (addr instanceof Inet4Address) {
                    ipv4Addr = addr;
                }
            }
        }
    }

    if (ipStartWith123 != null) {
        return ipStartWith123;
    } else if (ipv4Addr != null) {
        return ipv4Addr;
    }

    throw new RuntimeException("can not get WAN Address");
}

From source file:com.sentaroh.android.SMBSync2.CommonUtilities.java

public static String getIfIpAddress() {
    String result = "";
    try {//  w  ww . ja  va2s .c  om
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                //                  Log.v("","ip="+inetAddress.getHostAddress());
                if (!inetAddress.isLoopbackAddress() && (inetAddress.getHostAddress().startsWith("0")
                        || inetAddress.getHostAddress().startsWith("1")
                        || inetAddress.getHostAddress().startsWith("2"))) {
                    result = inetAddress.getHostAddress();
                    break;
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(APPLICATION_TAG, ex.toString());
        result = "192.168.0.1";
    }
    //      Log.v("","getIfIpAddress result="+result);
    if (result.equals(""))
        result = "192.168.0.1";
    return result;
}

From source file:org.apache.axis2.util.Utils.java

/**
* Returns the ip address to be used for the replyto epr
* CAUTION:/*from w w  w  . jav a  2  s  .  c  om*/
* This will go through all the available network interfaces and will try to return an ip address.
* First this will try to get the first IP which is not loopback address (127.0.0.1). If none is found
* then this will return this will return 127.0.0.1.
* This will <b>not<b> consider IPv6 addresses.
* <p/>
* TODO:
* - Improve this logic to genaralize it a bit more
* - Obtain the ip to be used here from the Call API
*
* @return Returns String.
* @throws java.net.SocketException
 */
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.clustercontrol.agent.Agent.java

public static AgentInfo getAgentInfo() {
    // IP???????agentInfo??????
    if (ReceiveTopic.isReloadFlg()) {
        return agentInfo;
    }//from  www  .  j a v a 2 s .c o  m

    agentInfo.setFacilityId(AgentProperties.getProperty("facilityId"));
    String instanceId = AgentProperties.getProperty("instanceId");
    if (instanceId == null) {
        instanceId = "";
    }
    agentInfo.setInstanceId(instanceId);

    // OS(?????IP)
    try {
        // ???
        String hostname = System.getProperty("hostname");
        m_log.debug("hostname=[" + hostname + "]");
        agentInfo.setHostname(hostname);

        // IP?
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        ArrayList<String> newIpAddressList = new ArrayList<String>();
        if (null != networkInterfaces) {
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress in = inetAddresses.nextElement();
                    String hostAddress = in.getHostAddress();
                    if (hostAddress != null && !hostAddress.equals("127.0.0.1")
                            && !hostAddress.startsWith("0:0:0:0:0:0:0:1") && !hostAddress.equals("::1")) {
                        newIpAddressList.add(hostAddress);
                    }
                }
            }
        }
        if (agentInfo.getIpAddress().size() != newIpAddressList.size()) {
            m_log.info("ipAddress change : " + agentInfo.getIpAddress().size() + "," + newIpAddressList.size());
            agentInfo.getIpAddress().clear();
            agentInfo.getIpAddress().addAll(newIpAddressList);
            ReceiveTopic.setReloadFlg(true);
        } else {
            if (!agentInfo.getIpAddress().containsAll(newIpAddressList)) {
                m_log.info("ipAddress change");
                agentInfo.getIpAddress().clear();
                agentInfo.getIpAddress().addAll(newIpAddressList);
                ReceiveTopic.setReloadFlg(true);
            }
        }
    } catch (SocketException e) {
        m_log.error(e, e);
    }
    agentInfo.setInterval(ReceiveTopic.getTopicInterval());

    m_log.debug(getAgentStr());

    return agentInfo;
}

From source file:com.sentaroh.android.SMBSync2.CommonUtilities.java

public static String getLocalIpAddress() {
    String result = "";
    boolean exit = false;
    try {//  w w  w .j a  va 2  s . c om
        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() && !(inetAddress.toString().indexOf(":")>=0)) {
                //                       return inetAddress.getHostAddress().toString();
                //                   }
                //                  Log.v("","ip="+inetAddress.getHostAddress()+
                //                        ", name="+intf.getName());
                if (inetAddress.isSiteLocalAddress()) {
                    result = inetAddress.getHostAddress();
                    //                       Log.v("","result="+result+", name="+intf.getName()+"-");
                    if (intf.getName().equals("wlan0")) {
                        exit = true;
                        break;
                    }
                }
            }
            if (exit)
                break;
        }
    } catch (SocketException ex) {
        Log.e(APPLICATION_TAG, ex.toString());
        result = "192.168.0.1";
    }
    //      Log.v("","getLocalIpAddress result="+result);
    if (result.equals(""))
        result = "192.168.0.1";
    return result;
}

From source file:com.petalmd.armor.AbstractUnitTest.java

public static String getNonLocalhostAddress() {
    try {/*from  w ww  .  j av  a2s  . c  om*/
        for (final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            final NetworkInterface intf = en.nextElement();

            if (intf.isLoopback() || !intf.isUp()) {
                continue;
            }

            for (final Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                    .hasMoreElements();) {

                final InetAddress ia = enumIpAddr.nextElement();

                if (ia.isLoopbackAddress() || ia instanceof Inet6Address) {
                    continue;
                }

                return ia.getHostAddress();
            }
        }
    } catch (final SocketException e) {
        throw new RuntimeException(e);

    }

    System.out.println("ERROR: No non-localhost address available, will use localhost");
    return "localhost";
}

From source file:com.flexive.shared.stream.FxStreamUtils.java

/**
 * Probe all network interfaces and return the most suited to run a StreamServer on.
 * Preferred are interfaces that are not site local.
 *
 * @return best suited host to run a StreamServer
 * @throws UnknownHostException on errors
 *///from w  ww. j  a  va2 s  . c om
public static InetAddress probeNetworkInterfaces() throws UnknownHostException {
    try {
        final String forcedAddress = System.getProperty("FxStreamIP");
        if (forcedAddress != null) {
            try {
                InetAddress ad = InetAddress.getByName(forcedAddress);
                LOG.info("Binding [fleXive] streamserver to forced address [" + forcedAddress + "] ...");
                return ad;
            } catch (UnknownHostException e) {
                LOG.error("Forced [fleXive] streamserver bind address [" + forcedAddress + "] can not be used: "
                        + e.getMessage() + " - probing available network interfaces ...");
            }
        }
        Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
        NetworkInterface nif;
        InetAddress preferred = null, fallback = null;
        while (nifs.hasMoreElements()) {
            nif = nifs.nextElement();
            if (LOG.isDebugEnabled())
                LOG.debug("Probing " + nif.getDisplayName() + " ...");
            if (nif.getDisplayName().startsWith("vmnet") || nif.getDisplayName().startsWith("vnet"))
                continue;
            Enumeration<InetAddress> inas = nif.getInetAddresses();
            while (inas.hasMoreElements()) {
                InetAddress na = inas.nextElement();
                if (LOG.isDebugEnabled())
                    LOG.debug("Probing " + nif.getDisplayName() + na);
                if (!(na instanceof Inet4Address))
                    continue;
                if (!na.isLoopbackAddress() && na.isReachable(1000)) {
                    if (preferred == null || (preferred.isSiteLocalAddress() && !na.isSiteLocalAddress()))
                        preferred = na;
                }
                if (fallback == null && na.isLoopbackAddress())
                    fallback = na;
            }
        }
        if (LOG.isDebugEnabled())
            LOG.debug("preferred: " + preferred + " fallback: " + fallback);
        if (preferred != null)
            return preferred;
        if (fallback != null)
            return fallback;
        return InetAddress.getLocalHost();
    } catch (Exception e) {
        return InetAddress.getLocalHost();
    }
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public static InetAddress getLocalInetAddress() throws SocketException {
    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())) {
                return inetAddress;
            }// ww w  .j a  v a2 s .  c  o  m
        }
    }

    return null;
}