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:com.offbynull.portmapper.common.NetworkUtils.java

/**
 * Get IP addresses for all interfaces on this machine that are IPv6.
 * @return IPv6 addresses assigned to this machine
 * @throws IOException if there's an error
 * @throws NullPointerException if any argument is {@code null}
 *///from www  .  j  a  v  a 2  s .c o m
public static Set<InetAddress> getAllLocalIpv6Addresses() throws IOException {
    Set<InetAddress> ret = new HashSet<>();

    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
        Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
        while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
            InetAddress addr = addrs.nextElement();

            if (addr instanceof Inet6Address && !addr.isAnyLocalAddress()) {
                ret.add(addr);
            }
        }
    }

    return ret;
}

From source file:com.chicm.cmraft.core.ClusterMemberManager.java

private void initLocalAddresses() {
    try {/*from   w w  w  .  j a  v  a2 s .  co  m*/
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface inet = (NetworkInterface) interfaces.nextElement();
            Enumeration<InetAddress> addrs = inet.getInetAddresses();
            while (addrs.hasMoreElements()) {
                InetAddress addr = (InetAddress) addrs.nextElement();
                LOG.debug("local address:" + addr.getHostAddress());
                LOG.debug("local address:" + addr.getHostName());
                if (!addr.getHostAddress().isEmpty()) {
                    localAddresses.add(addr.getHostAddress());
                }
                if (!addr.getHostName().isEmpty()) {
                    localAddresses.add(addr.getHostName());
                }
            }
        }

        InetAddress inetAddress = InetAddress.getLocalHost();
        localAddresses.add(inetAddress.getHostAddress());
        localAddresses.add(inetAddress.getCanonicalHostName());
        localAddresses.add(inetAddress.getHostName());

        inetAddress = InetAddress.getLoopbackAddress();
        localAddresses.add(inetAddress.getHostAddress());
        localAddresses.add(inetAddress.getCanonicalHostName());
        localAddresses.add(inetAddress.getHostName());
    } catch (SocketException | UnknownHostException e) {
        LOG.error("", e);
    }
}

From source file:com.shreymalhotra.crazyflieserver.MainActivity.java

public String getLocalIpAddress() {
    try {//from w w w  . j a v  a2  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.isLinkLocalAddress() &&
                // inetAddress.isSiteLocalAddress() ) {
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                    String ipAddr = inetAddress.getHostAddress();
                    return ipAddr;
                }
            }
        }
    } catch (SocketException ex) {
        Log.d("CrazyFlieServer", ex.toString());
    }
    return null;
}

From source file:com.vinexs.tool.NetworkManager.java

public static String getIPAddress(boolean useIPv4) {
    try {/*  www .  j a v  a 2s. c o m*/
        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 = InetAddressUtilsHC4.isIPv4Address(sAddr);
                    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 e) {
        e.printStackTrace();
    }
    return "";
}

From source file:org.apache.hama.zookeeper.QuorumPeer.java

private static void writeMyID(Properties properties) throws IOException {
    long myId = -1;

    Configuration conf = new HamaConfiguration();
    String myAddress = DNS.getDefaultHost(conf.get("hama.zookeeper.dns.interface", "default"),
            conf.get("hama.zookeeper.dns.nameserver", "default"));

    List<String> ips = new ArrayList<String>();

    // Add what could be the best (configured) match
    ips.add(myAddress.contains(".") ? myAddress : StringUtils.simpleHostname(myAddress));

    // For all nics get all hostnames and IPs
    Enumeration<?> nics = NetworkInterface.getNetworkInterfaces();
    while (nics.hasMoreElements()) {
        Enumeration<?> rawAdrs = ((NetworkInterface) nics.nextElement()).getInetAddresses();
        while (rawAdrs.hasMoreElements()) {
            InetAddress inet = (InetAddress) rawAdrs.nextElement();
            ips.add(StringUtils.simpleHostname(inet.getHostName()));
            ips.add(inet.getHostAddress());
        }//from w w  w.  j a v  a  2  s .  co m
    }

    for (Entry<Object, Object> entry : properties.entrySet()) {
        String key = entry.getKey().toString().trim();
        String value = entry.getValue().toString().trim();

        if (key.startsWith("server.")) {
            int dot = key.indexOf('.');
            long id = Long.parseLong(key.substring(dot + 1));
            String[] parts = value.split(":");
            String address = parts[0];
            if (addressIsLocalHost(address) || ips.contains(address)) {
                myId = id;
                break;
            }
        }
    }

    if (myId == -1) {
        throw new IOException(
                "Could not find my address: " + myAddress + " in list of ZooKeeper quorum servers");
    }

    String dataDirStr = properties.get("dataDir").toString().trim();
    File dataDir = new File(dataDirStr);
    if (!dataDir.isDirectory()) {
        if (!dataDir.mkdirs()) {
            throw new IOException("Unable to create data dir " + dataDir);
        }
    }

    File myIdFile = new File(dataDir, "myid");
    PrintWriter w = new PrintWriter(myIdFile);
    w.println(myId);
    w.close();
}

From source file:org.apereo.portal.PortalInfoProviderImpl.java

protected String getDefaultNetworkInterfaceName() {
    this.logger/*  www  .  java  2s .  co  m*/
            .info("Attempting to resolve serverName by iterating over NetworkInterface.getNetworkInterfaces()");

    //Fail back to our best attempt at resolution
    final Enumeration<NetworkInterface> networkInterfaceEnum;
    try {
        networkInterfaceEnum = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.warn("Failed to get list of available NetworkInterfaces.", e);
        return null;
    }

    //Use a local variable here to try and return the first hostName found that doesn't start with localhost
    String name = null;
    while (networkInterfaceEnum.hasMoreElements()) {
        final NetworkInterface networkInterface = networkInterfaceEnum.nextElement();

        for (Enumeration<InetAddress> inetAddressEnum = networkInterface.getInetAddresses(); inetAddressEnum
                .hasMoreElements();) {
            final InetAddress inetAddress = inetAddressEnum.nextElement();
            name = inetAddress.getHostName();
            if (!name.startsWith("localhost")) {
                return name;
            }
        }
    }

    return name;
}

From source file:com.DPFaragir.DPFUtils.java

public static String getIPAddress(boolean useIPv4) {
    try {/* w  w  w .ja  v  a  2 s .c o m*/
        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 (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 "";
}

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

public static String getIpAddress() {
    try {//  w w  w . j  a  va2  s  . c o  m
        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:edu.ucsb.eucalyptus.ic.WalrusReplyQueue.java

public void handle(ExceptionMessage muleMsg) {
    try {/*from  w  w w  .  java2s.c o m*/
        Object requestMsg = muleMsg.getPayload();
        String requestString = requestMsg.toString();
        EucalyptusMessage msg = (EucalyptusMessage) BindingManager.getBinding("msgs_eucalyptus_ucsb_edu")
                .fromOM(requestString);
        Throwable ex = muleMsg.getException().getCause();
        EucalyptusMessage errMsg;

        String ipAddr = "127.0.0.1";
        List<NetworkInterface> ifaces = null;
        try {
            ifaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        } catch (SocketException e1) {
        }

        for (NetworkInterface iface : ifaces) {
            try {
                if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp()) {
                    for (InetAddress iaddr : Collections.list(iface.getInetAddresses())) {
                        if (!iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) {
                            ipAddr = iaddr.getHostAddress();
                            break;
                        }
                    }
                }
            } catch (SocketException e1) {
            }
        }

        if (ex instanceof NoSuchBucketException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchBucketException) ex).getBucketName(),
                    "NoSuchBucket", "The specified bucket was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof AccessDeniedException) {
            errMsg = new WalrusBucketErrorMessageType(((AccessDeniedException) ex).getBucketName(),
                    "AccessDenied", "No U", HttpStatus.SC_FORBIDDEN, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotAuthorizedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotAuthorizedException) ex).getValue(), "Unauthorized",
                    "No U", HttpStatus.SC_UNAUTHORIZED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyOwnedByYouException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyOwnedByYouException) ex).getBucketName(),
                    "BucketAlreadyOwnedByYou",
                    "Your previous request to create the named bucket succeeded and you already own it.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyExistsException) ex).getBucketName(),
                    "BucketAlreadyExists",
                    "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.",
                    HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof BucketNotEmptyException) {
            errMsg = new WalrusBucketErrorMessageType(((BucketNotEmptyException) ex).getBucketName(),
                    "BucketNotEmpty", "The bucket you tried to delete is not empty.", HttpStatus.SC_CONFLICT,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof PreconditionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((PreconditionFailedException) ex).getPrecondition(),
                    "PreconditionFailed", "At least one of the pre-conditions you specified did not hold.",
                    HttpStatus.SC_PRECONDITION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotModifiedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotModifiedException) ex).getPrecondition(),
                    "NotModified", "Object Not Modified", HttpStatus.SC_NOT_MODIFIED, msg.getCorrelationId(),
                    ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof TooManyBucketsException) {
            errMsg = new WalrusBucketErrorMessageType(((TooManyBucketsException) ex).getBucketName(),
                    "TooManyBuckets", "You have attempted to create more buckets than allowed.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof EntityTooLargeException) {
            errMsg = new WalrusBucketErrorMessageType(((EntityTooLargeException) ex).getEntityName(),
                    "EntityTooLarge", "Your proposed upload exceeds the maximum allowed object size.",
                    HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NoSuchEntityException) {
            errMsg = new WalrusBucketErrorMessageType(((NoSuchEntityException) ex).getBucketName(),
                    "NoSuchEntity", "The specified entity was not found", HttpStatus.SC_NOT_FOUND,
                    msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof DecryptionFailedException) {
            errMsg = new WalrusBucketErrorMessageType(((DecryptionFailedException) ex).getValue(),
                    "Decryption Failed", "Fail", SC_DECRYPTION_FAILED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof ImageAlreadyExistsException) {
            errMsg = new WalrusBucketErrorMessageType(((ImageAlreadyExistsException) ex).getValue(),
                    "Image Already Exists", "Fail", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else if (ex instanceof NotImplementedException) {
            errMsg = new WalrusBucketErrorMessageType(((NotImplementedException) ex).getValue(),
                    "Not Implemented", "NA", HttpStatus.SC_NOT_IMPLEMENTED, msg.getCorrelationId(), ipAddr);
            errMsg.setCorrelationId(msg.getCorrelationId());
        } else {
            errMsg = new EucalyptusErrorMessageType(muleMsg.getComponentName(), msg, ex.getMessage());
        }
        replies.putMessage(errMsg);
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:net.centro.rtb.monitoringcenter.infos.NodeInfo.java

private static String detectLoadBalancerIpAddress() {
    Enumeration<NetworkInterface> networkInterfaces = null;
    try {/*  w  w w. jav  a2 s  . co m*/
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.debug("Unable to obtain network interfaces!", e);
        return null;
    }

    for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
        boolean isLoopback = false;
        try {
            isLoopback = networkInterface.isLoopback();
        } catch (SocketException e) {
            logger.debug("Unable to identify if a network interface is a loopback or not");
            continue;
        }

        if (isLoopback) {
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress() && Inet4Address.class.isInstance(inetAddress)) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    }

    return null;
}