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:org.lnicholls.galleon.util.Tools.java

public static boolean isLocalAddress(String address) {
    if (address != null) {
        try {//from w  ww  .j av  a 2 s. co  m
            for (Enumeration interfaceEnum = NetworkInterface.getNetworkInterfaces(); interfaceEnum
                    .hasMoreElements();) {
                NetworkInterface ni = (NetworkInterface) interfaceEnum.nextElement();
                Enumeration inetAddresses = ni.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
                    if (inetAddress.getHostAddress().equals(address))
                        return true;
                }
            }
        } catch (Exception ex) {
            Tools.logException(Tools.class, ex);
        }
    }
    return false;
}

From source file:org.opendaylight.ovsdb.openstack.netvirt.impl.BridgeConfigurationManagerImpl.java

private String getControllerTarget() {
    /* TODO SB_MIGRATION
     * hardcoding value, need to find better way to get local ip
     *///from   w  w w .j  a  va  2 s .c  o  m
    //String target = "tcp:" + getControllerIPAddress() + ":" + getControllerOFPort();
    //TODO: dirty fix, need to remove it once we have proper solution
    String ipaddress = null;
    try {
        for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();

            for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {
                    if (inetAddr.isSiteLocalAddress()) {
                        ipaddress = inetAddr.getHostAddress();
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.warn("ROYALLY SCREWED : Exception while fetching local host ip address ", e);
    }
    return "tcp:" + ipaddress + ":6633";
}

From source file:org.rifidi.utilities.device.DeviceAddressManager.java

/**
 * This method enumerates all existing devices in the system.
 *///from   w ww.  ja  v a 2s  .com
@SuppressWarnings("unchecked")
private void enumerateSystemDevices() {
    /* This is the set which will eventually become the new device set */
    Set<SystemDevice> enumeratedDevices = new TreeSet<SystemDevice>();

    /* Grab the previous devices and put them in an easy to use list form */
    List<SystemDevice> previouslyEnumeratedDevices = new ArrayList<SystemDevice>(this.systemDevices);

    /* Enumerate serial devices */
    if (this.serialEnabled) {
        Enumeration commPorts = CommPortIdentifier.getPortIdentifiers();
        while (commPorts.hasMoreElements()) {
            CommPortIdentifier curCommPort = (CommPortIdentifier) commPorts.nextElement();
            if (curCommPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                /* Make a serial port so that we can get baud settings, etc. */
                RXTXPort tempPort = null;

                try {
                    /*
                     * Grab the serial port and get all of its current
                     * settings
                     */
                    tempPort = new RXTXPort(curCommPort.getName());

                    SystemSerialPort portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(),
                            SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING, tempPort.getBaudRate(),
                            tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits());

                    /* Check and see if the device already exists */
                    int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(portToAdd);
                    if (existingDeviceIndex != -1) {
                        /* Grab that already existing device */
                        SystemSerialPort existingSerialDevice = (SystemSerialPort) previouslyEnumeratedDevices
                                .get(existingDeviceIndex);

                        /* Copy the creation state over */
                        portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(),
                                existingSerialDevice.getDeviceExistenceType(), tempPort.getBaudRate(),
                                tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits());

                    }

                    tempPort.close();

                    /* Add to enumerated devices */
                    enumeratedDevices.add(portToAdd);

                } catch (PortInUseException e) {
                    logger.info(e.getMessage() + " (" + curCommPort.getName() + ")");

                }

            }

        }

    }

    /* Enumerate IP devices and all addresses. */
    /* Get all of the interfaces in the system and print them. */
    Enumeration<NetworkInterface> netInterfaces = null;

    try {
        netInterfaces = NetworkInterface.getNetworkInterfaces();

    } catch (SocketException e) {
        logger.warn(e.getMessage());

    }

    /* Check to see if we have interfaces to add to the device list. */
    if (netInterfaces != null) {
        /* Grab all of the interfaces and their network addresses */
        while (netInterfaces.hasMoreElements()) {
            /* Grab the current interface */
            NetworkInterface curInterface = netInterfaces.nextElement();

            /* Use a tree map for sorted IPs */
            Map<String, SystemNetworkInterface.NetworkAddressType> curInterfaceAddressMap;
            curInterfaceAddressMap = new TreeMap<String, SystemNetworkInterface.NetworkAddressType>();

            /* Get all of the addresses which this interface has */
            Enumeration<InetAddress> curInterfaceAddresses = curInterface.getInetAddresses();

            while (curInterfaceAddresses.hasMoreElements()) {
                /* Append the current address to map */
                InetAddress curAddress = curInterfaceAddresses.nextElement();
                curInterfaceAddressMap.put(curAddress.getHostAddress(),
                        SystemNetworkInterface.NetworkAddressType.PREVIOUSLY_EXISTING);

            }

            /* Create the new device */
            SystemNetworkInterface interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(),
                    curInterface.getName(), SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING,
                    curInterfaceAddressMap);

            /* Check and see if the device already exists */
            int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(interfaceToAdd);
            if (existingDeviceIndex != -1) {
                /* Grab that already existing device */
                SystemNetworkInterface existingNetworkInterface = (SystemNetworkInterface) previouslyEnumeratedDevices
                        .get(existingDeviceIndex);

                /* Copy over the existing device existence type */
                interfaceToAdd = null;
                interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(),
                        curInterface.getName(), existingNetworkInterface.getDeviceExistenceType(),
                        curInterfaceAddressMap);

                /* Copy over the address info */
                Iterator<String> addressIter = interfaceToAdd.getNetworkAddresses().keySet().iterator();
                /* Check each IP and see if it is previously existing */
                while (addressIter.hasNext()) {
                    String curAddress = addressIter.next();
                    SystemNetworkInterface.NetworkAddressType existingType = existingNetworkInterface
                            .getNetworkAddresses().get(curAddress);
                    /* Preserve the existing type */
                    if (existingType != null) {
                        interfaceToAdd.getNetworkAddresses().put(curAddress, existingType);

                    }

                }

            }

            /* Add the new device to the existing devices list */
            enumeratedDevices.add(interfaceToAdd);

        }

    }

    /* Blow out the old system devices */
    this.systemDevices.clear();

    /* Assign the new system devices */
    this.systemDevices = enumeratedDevices;

}

From source file:util.Control.java

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

From source file:org.ohthehumanity.carrie.CarrieActivity.java

public String getLocalIpAddress() {
    try {//  w w  w  . j a  v  a2s .  c o  m
        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()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        //Log.e(TAG, ex.toString());
    }
    return "";
}

From source file:edu.umass.cs.gigapaxos.testing.TESTPaxosConfig.java

/**
 * @param myID/*from ww  w  .j  av a2s.  c om*/
 * @return True if found my IP.
 * @throws SocketException
 */
public static boolean findMyIP(Integer myID) throws SocketException {
    if (myID == null)
        return false;
    Enumeration<NetworkInterface> netfaces = NetworkInterface.getNetworkInterfaces();
    ArrayList<InetAddress> myIPs = new ArrayList<InetAddress>();
    while (netfaces.hasMoreElements()) {
        NetworkInterface iface = netfaces.nextElement();
        Enumeration<InetAddress> allIPs = iface.getInetAddresses();
        while (allIPs.hasMoreElements()) {
            InetAddress addr = allIPs.nextElement();
            if ((addr instanceof Inet4Address))
                myIPs.add((InetAddress) addr);
        }
    }
    System.out.println(myIPs);
    boolean found = false;
    if (myIPs.contains(getNodeConfig().getNodeAddress(myID))) {
        found = true;
    }
    if (found)
        System.out.println("Found my IP");
    else {
        System.out.println("\n\n****Could not locally find the IP " + getNodeConfig().getNodeAddress(myID)
                + "; should change all addresses to localhost instead.****\n\n.");
    }
    return found;
}

From source file:org.apache.synapse.transport.passthru.api.PassThroughNHttpGetProcessor.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 w  w  w .ja  v a  2  s  . co  m
* @throws java.net.SocketException if the socket can not be accessed
*/
protected static String getIpAddress() throws SocketException {
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    String address = "127.0.0.1";

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

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

From source file:org.wso2.carbon.apimgt.hybrid.gateway.configurator.Configurator.java

/**
 * Retrieve host name, mac address of the device
 *
 * @return details Map<String, String>
 *//*from  w  w  w  .j a  v a  2s.c o m*/
protected static Map<String, String> getDeviceDetails() {
    InetAddress ip;
    String hostName = "";
    String macAddress = ConfigConstants.DEFAULT_MAC_ADDRESS;
    Map<String, String> details = new HashMap();
    try {
        ip = InetAddress.getLocalHost();
        hostName = ip.getHostName();
        Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaceEnumeration.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
            Enumeration<InetAddress> enumeration = networkInterface.getInetAddresses();
            for (; enumeration.hasMoreElements();) {
                InetAddress address = enumeration.nextElement();
                if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()
                        && address.isSiteLocalAddress()) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            //Construct mac address
                            sb.append(String.format("%02X%s", mac[i],
                                    (i < mac.length - 1) ? ConfigConstants.DELIMITER : ""));
                        }
                        macAddress = sb.toString();
                        break;
                    }
                }
            }
        }
    } catch (UnknownHostException | SocketException e) {
        log.error("Error while retrieving mac address", e);
        Runtime.getRuntime().exit(1);
    }
    details.put(ConfigConstants.HOST_NAME, hostName);
    details.put(ConfigConstants.MAC_ADDRESS, macAddress);
    return details;
}

From source file:org.lnicholls.galleon.util.Tools.java

public static boolean isLocal(String address) {
    if (address != null) {
        try {/* w w  w .  j a  v a2 s.  c o  m*/
            if (address.equals("127.0.0.1"))
                return true;
            String prefix = null;
            StringTokenizer tokenizer = new StringTokenizer(address, ".");
            if (tokenizer.hasMoreTokens())
                prefix = tokenizer.nextToken();
            if (prefix != null) {
                for (Enumeration interfaceEnum = NetworkInterface.getNetworkInterfaces(); interfaceEnum
                        .hasMoreElements();) {
                    NetworkInterface ni = (NetworkInterface) interfaceEnum.nextElement();
                    Enumeration inetAddresses = ni.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
                        if (inetAddress.getHostAddress().startsWith(prefix))
                            return true;
                    }
                }
            }
        } catch (Exception ex) {
            Tools.logException(Tools.class, ex);
        }
    }
    return false;
}