Example usage for java.net NetworkInterface getInterfaceAddresses

List of usage examples for java.net NetworkInterface getInterfaceAddresses

Introduction

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

Prototype

public java.util.List<InterfaceAddress> getInterfaceAddresses() 

Source Link

Document

Get a List of all or a subset of the InterfaceAddresses of this network interface.

Usage

From source file:Main.java

public static InterfaceAddress getInterfaceAddress(NetworkInterface intf) {
    try {// w  w w.  j  a va  2s  .  co  m
        InterfaceAddress res = null;
        for (Iterator<InterfaceAddress> iterIntAddr = intf.getInterfaceAddresses().iterator(); iterIntAddr
                .hasNext();) {
            InterfaceAddress intAddress = iterIntAddr.next();
            if (!intAddress.getAddress().isLoopbackAddress()) {
                if (isIpv4(intAddress.getAddress()))
                    return intAddress;
                else
                    res = intAddress;
            }
        }
        if (res != null)
            return res;
    } catch (Exception e) {
    }

    return null;
}

From source file:de.uni_bonn.bit.IPAddressHelper.java

/**
 * Returns a list of IP addresses that can be used to communicate with a peer on a
 * different machine. The IP addresses are in CIDR notation (e.g. 192.168.2.1/24).
 * @return//from w  w w .ja va 2  s.  c  o  m
 */
public static List<String> getAllUsableIPAddresses() {
    List<String> output = new ArrayList<String>();
    try {
        for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            for (InterfaceAddress address : ni.getInterfaceAddresses()) {
                if (!address.getAddress().isMulticastAddress() && !address.getAddress().isLinkLocalAddress()
                        && !address.getAddress().isLoopbackAddress()) {
                    output.add(address.getAddress().getHostAddress() + "/" + address.getNetworkPrefixLength());
                }
            }
        }
    } catch (SocketException e) {

    }
    return output;
}

From source file:com.clustercontrol.repository.util.NodeSearchUtil.java

/**
 * Generate default IP for node search/create dialog
 *///from ww w .  j  a  v a  2s  .c om
public static String generateDefaultIp(String def, int hostAddress) {
    try {
        // Get IP
        InetAddress addr = Inet4Address.getLocalHost();

        // Get subnet mask length
        int prefixLength = -1;
        NetworkInterface ni = NetworkInterface.getByInetAddress(addr);
        for (InterfaceAddress iaddr : ni.getInterfaceAddresses()) {
            if (iaddr.getAddress() instanceof Inet4Address) {
                prefixLength = iaddr.getNetworkPrefixLength();
                break;
            }
        }
        if (-1 == prefixLength) {
            return def;
        }

        byte[] ipRaw = addr.getAddress();
        // For ipv4
        if (4 == ipRaw.length) {
            int counter = prefixLength;
            for (int i = 0; i < ipRaw.length; i++) {
                if (counter < 8) {
                    byte mask = 0x00;
                    for (int j = 0; j < counter; j++) {
                        mask = (byte) (mask >> 1 | 0x80);
                    }
                    ipRaw[i] = (byte) (ipRaw[i] & mask);
                }
                counter -= 8;
            }

            // Re-format/round up hostAddress
            if (hostAddress < 0) {
                hostAddress += Math.pow(2, 32 - prefixLength);
            }

            // Add host address part
            int part = 4;
            while (hostAddress > 0 && part > 0) {
                ipRaw[part - 1] += (hostAddress & 0xff);
                hostAddress >>= 8;
            }
            return Inet4Address.getByAddress(ipRaw).getHostAddress();
        }
        // TODO Support ipv6?
    } catch (UnknownHostException | SocketException e) {
        m_log.debug(e);
    }
    return def;
}

From source file:com.redhat.rhn.domain.monitoring.satcluster.SatClusterFactory.java

/**
 * Create a new SatCluster (scout)//from   w w w  . jav a  2 s  .com
 * @param user who creates the Scout
 * @return new instance
 */
public static SatCluster createSatCluster(User user) {
    SatCluster retval = new SatCluster();
    CommandTarget ct = new CommandTarget();
    ct.setOrg(user.getOrg());
    ct.setTargetType("cluster");
    retval.setCommandTarget(ct);
    retval.setOrg(user.getOrg());
    retval.setPhysicalLocation(PHYSICAL_LOCATION);
    retval.setTargetType(ct.getTargetType());
    retval.setDeployed("1");
    retval.setLastUpdateUser(user.getLogin());
    retval.setLastUpdateDate(new Date());
    try {
        InetAddress ip = InetAddress.getLocalHost();
        boolean haveIpv4 = ip instanceof Inet4Address;
        if (haveIpv4) {
            retval.setVip(ip.getHostAddress());
        } else {
            retval.setVip6(ip.getHostAddress());
        }
        NetworkInterface ni = NetworkInterface.getByInetAddress(ip);
        for (InterfaceAddress ifa : ni.getInterfaceAddresses()) {
            InetAddress ia = ifa.getAddress();
            if ((ia instanceof Inet4Address) != haveIpv4) {
                if (haveIpv4) {
                    retval.setVip6(ia.getHostAddress());
                } else {
                    retval.setVip(ia.getHostAddress());
                }
                break;
            }
        }
    } catch (Exception e) {
        log.warn("Failed to find out IP host addresses. " + "Setting loopback IPs instead.");
        try {
            NetworkInterface ni = NetworkInterface.getByName("lo");
            for (InterfaceAddress ifa : ni.getInterfaceAddresses()) {
                InetAddress ia = ifa.getAddress();
                if (ia instanceof Inet4Address) {
                    if (StringUtils.isEmpty(retval.getVip())) {
                        retval.setVip(ia.getHostAddress());
                    }
                } else { //IPv6
                    if (StringUtils.isEmpty(retval.getVip6())) {
                        retval.setVip6(ia.getHostAddress());
                    }
                }
            }
        } catch (SocketException se) {
            log.fatal("Failed to find out loopback IPs.");
            se.printStackTrace();
        }
    }
    return retval;
}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils.java

public static String findAvailableHostAddress() throws UnknownHostException, SocketException {
    InetAddress address = InetAddress.getLocalHost();
    if (address.isLoopbackAddress()) {
        for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            if (!networkInterface.isLoopback()) {
                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                    InetAddress a = interfaceAddress.getAddress();
                    if (a instanceof Inet4Address) {
                        return a.getHostAddress();
                    }/*  w  ww  .j a  va 2 s.  c  om*/
                }
            }
        }
    }
    return address.getHostAddress();
}

From source file:org.openhab.binding.network.service.NetworkUtils.java

/**
 * Gets every IPv4 Address on each Interface except the loopback
 * The Address format is ip/subnet//from  www .  j  a v  a2s  . c  o m
 *
 * @return The collected IPv4 Addresses
 */
public static TreeSet<String> getInterfaceIPs() {
    TreeSet<String> interfaceIPs = new TreeSet<String>();

    try {
        // For each interface ...
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface networkInterface = en.nextElement();
            if (!networkInterface.isLoopback()) {

                // .. and for each address ...
                for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it
                        .hasNext();) {

                    // ... get IP and Subnet
                    InterfaceAddress interfaceAddress = it.next();
                    interfaceIPs.add(interfaceAddress.getAddress().getHostAddress() + "/"
                            + interfaceAddress.getNetworkPrefixLength());
                }
            }
        }
    } catch (SocketException e) {
    }

    return interfaceIPs;
}

From source file:es.upv.grc.grcbox.server.GrcBoxServerApplication.java

private static void startServer(String string) throws Exception {
    Component androPiComponent = new Component();
    NetworkInterface iface = NetworkInterface.getByName(string);
    if (iface == null) {
        System.err.println("ERROR: No inner  interface called " + string + " exists");
        System.exit(-1);/*ww  w  . j a  v a2 s.c om*/
    }
    List<InterfaceAddress> addresses = iface.getInterfaceAddresses();
    InterfaceAddress addr = null;
    for (InterfaceAddress interfaceAddress : addresses) {
        if (interfaceAddress.getAddress() instanceof Inet4Address) {
            addr = interfaceAddress;
            break;
        }
    }

    if (addr != null) {
        Server server = androPiComponent.getServers().add(Protocol.HTTP, addr.getAddress().getHostAddress(),
                8080);
        androPiComponent.getDefaultHost().attach(new GrcBoxServerApplication());
        androPiComponent.start();
    } else {
        LOG.severe("The server could not be initialized. No Ipv4 address on innerinterface present");
        System.exit(1);
    }
}

From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java

/**
 * Returns the last adapter it finds that is not a loopback
 *
 * @return Adapter to use/* www  . ja v  a  2s .co  m*/
 */
public static List<NetworkInterface> getNetworkAdapters() {
    List<NetworkInterface> returnValue = new ArrayList<NetworkInterface>();
    try {

        // Loop round all the adapters

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {

            // Get the MAC address if it exists

            NetworkInterface network = networkInterfaces.nextElement();
            byte[] mac = network.getHardwareAddress();
            if (mac != null && mac.length > 0 && network.getInterfaceAddresses() != null) {
                returnValue.add(network);
                logger.debug("Current MAC address : {} ({})", returnValue, network.getDisplayName());
            }
        }
    } catch (Exception e) {
        logger.error("Cannot determine the local MAC address - {}", e.getMessage());
    }
    return returnValue;
}

From source file:org.openhab.binding.network.service.NetworkService.java

/**
 * Gets every IPv4 Address on each Interface except the loopback
 * The Address format is ip/subnet//w ww  . j a v  a2  s  . c  o m
 *
 * @return The collected IPv4 Addresses
 */
private static TreeSet<String> getInterfaceIPs() {
    TreeSet<String> interfaceIPs = new TreeSet<String>();

    try {
        // For each interface ...
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface networkInterface = en.nextElement();
            if (!networkInterface.isLoopback()) {

                // .. and for each address ...
                for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it
                        .hasNext();) {

                    // ... get IP and Subnet
                    InterfaceAddress interfaceAddress = it.next();
                    interfaceIPs.add(interfaceAddress.getAddress().getHostAddress() + "/"
                            + interfaceAddress.getNetworkPrefixLength());
                }
            }
        }
    } catch (SocketException e) {
    }

    return interfaceIPs;
}

From source file:nz.co.fortytwo.signalk.util.Util.java

public static boolean sameNetwork(String localAddress, String remoteAddress) throws Exception {
    InetAddress addr = InetAddress.getByName(localAddress);
    NetworkInterface networkInterface = NetworkInterface.getByInetAddress(addr);
    short netmask = -1;
    for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
        if (address.getAddress().equals(addr)) {
            netmask = address.getNetworkPrefixLength();
        }//from   w w  w .  java2s.com
    }
    byte[] a1 = InetAddress.getByName(localAddress).getAddress();
    byte[] a2 = InetAddress.getByName(remoteAddress).getAddress();
    byte[] m = InetAddress.getByName(normalizeFromCIDR(netmask)).getAddress();

    for (int i = 0; i < a1.length; i++)
        if ((a1[i] & m[i]) != (a2[i] & m[i]))
            return false;

    return true;

}