Example usage for java.net NetworkInterface isUp

List of usage examples for java.net NetworkInterface isUp

Introduction

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

Prototype


public boolean isUp() throws SocketException 

Source Link

Document

Returns whether a network interface is up and running.

Usage

From source file:org.openhab.binding.plclogo.internal.discovery.PLCDiscoveryService.java

@Override
protected void startScan() {
    stopScan();/*w  w w .j  a v a  2  s. c o  m*/

    logger.debug("Start scan for LOGO! bridge");

    Enumeration<NetworkInterface> devices = null;
    try {
        devices = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException exception) {
        logger.warn("LOGO! bridge discovering: {}.", exception.toString());
    }

    Set<String> addresses = new TreeSet<>();
    while ((devices != null) && devices.hasMoreElements()) {
        NetworkInterface device = devices.nextElement();
        try {
            if (!device.isUp() || device.isLoopback()) {
                continue;
            }
        } catch (SocketException exception) {
            logger.warn("LOGO! bridge discovering: {}.", exception.toString());
        }
        for (InterfaceAddress iface : device.getInterfaceAddresses()) {
            InetAddress address = iface.getAddress();
            if (address instanceof Inet4Address) {
                String prefix = String.valueOf(iface.getNetworkPrefixLength());
                SubnetUtils utilities = new SubnetUtils(address.getHostAddress() + "/" + prefix);
                addresses.addAll(Arrays.asList(utilities.getInfo().getAllAddresses()));
            }
        }
    }

    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (String address : addresses) {
        try {
            executor.execute(new Runner(address));
        } catch (RejectedExecutionException exception) {
            logger.warn("LOGO! bridge discovering: {}.", exception.toString());
        }
    }

    try {
        executor.awaitTermination(CONNECTION_TIMEOUT * addresses.size(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException exception) {
        logger.warn("LOGO! bridge discovering: {}.", exception.toString());
    }
    executor.shutdown();

    stopScan();
}

From source file:com.almende.arum.EventPusher.java

private String getHostAddress() throws SocketException {
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        if (!n.isLoopback() && n.isUp() && !n.isVirtual()) {

            Enumeration<InetAddress> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                if (i instanceof Inet4Address && !i.isLinkLocalAddress() && !i.isMulticastAddress()) {
                    return i.getHostAddress().trim();
                }//from  w  w w.j av a 2s.co  m
            }
        }
    }
    return null;
}

From source file:org.springframework.cloud.commons.util.InetUtils.java

public InetAddress findFirstNonLoopbackAddress() {
    InetAddress result = null;//from w w w .java2s .  co  m
    try {
        int lowest = Integer.MAX_VALUE;
        for (Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); nics
                .hasMoreElements();) {
            NetworkInterface ifc = nics.nextElement();
            if (ifc.isUp()) {
                log.trace("Testing interface: " + ifc.getDisplayName());
                if (ifc.getIndex() < lowest || result == null) {
                    lowest = ifc.getIndex();
                } else if (result != null) {
                    continue;
                }

                // @formatter:off
                if (!ignoreInterface(ifc.getDisplayName())) {
                    for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) {
                        InetAddress address = addrs.nextElement();
                        if (address instanceof Inet4Address && !address.isLoopbackAddress()
                                && !ignoreAddress(address)) {
                            log.trace("Found non-loopback interface: " + ifc.getDisplayName());
                            result = address;
                        }
                    }
                }
                // @formatter:on
            }
        }
    } catch (IOException ex) {
        log.error("Cannot get first non-loopback address", ex);
    }

    if (result != null) {
        return result;
    }

    try {
        return InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        log.warn("Unable to retrieve localhost");
    }

    return null;
}

From source file:de.micromata.mgc.application.webserver.config.JettyConfigTabController.java

private List<String> getListenHosts() {
    List<String> ret = new ArrayList<>();
    try {//  ww  w .j a v a2s .c  om
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            if (n.isUp() == false) {
                continue;
            }
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                //          ret.add(i.getHostName());
                ret.add(i.getHostAddress());
                //          System.out.println(i.getHostAddress());
            }
        }
    } catch (Exception ex) {
        ValMessage vm = new ValMessage(ValState.Error, "");
        vm.setMessage("Error retriving hosts: " + ex.getMessage());
        addToFeedback(vm);
    }
    return ret;
}

From source file:org.apache.spark.simr.Simr.java

/**
 * @return The IP of the first network interface on this machine as a string, null in the case
 * of an exception from the underlying network interface.
 *///from w ww  .ja v  a 2s  . c o m
public String getLocalIP() {
    String ip;
    int pickIfaceNum = conf.getInt("simr_interface", 0);

    int currIface = 0;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();

            if (iface.isLoopback() || !iface.isUp())
                continue;

            if (currIface++ >= pickIfaceNum) {
                Enumeration<InetAddress> addresses = iface.getInetAddresses();

                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr instanceof Inet4Address) {
                        ip = addr.getHostAddress();
                        return ip;
                    }
                }
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.onosproject.ospf.controller.impl.Controller.java

/**
 * Tell controller that we're ready to handle channels.
 *//*from   w w w.ja  v  a  2 s .com*/
public void run() {
    try {
        //get the configuration from json file
        List<OSPFArea> areas = getConfiguration();
        //get the connected interfaces
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        // Check NetworkInterfaces and area-config have same IP Address
        for (NetworkInterface netInt : Collections.list(nets)) {
            // if the interface is up & not loopback
            if (!netInt.isUp() && !netInt.isLoopback()) {
                continue;
            }
            //get all the InetAddresses
            Enumeration<InetAddress> inetAddresses = netInt.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                String ipAddress = inetAddress.getHostAddress();
                //Search for the address in all configured areas interfaces
                for (OSPFArea area : areas) {
                    for (OSPFInterface ospfIf : area.getInterfacesLst()) {
                        String ipFromConfig = ospfIf.getIpAddress();
                        if (ipFromConfig.trim().equals(ipAddress.trim())) {
                            log.debug("Both Config and Interface have ipAddress {} for area {}", ipAddress,
                                    area.getAreaID());
                            // if same IP address create
                            try {
                                log.debug("Creating ServerBootstrap for {} @ {}", ipAddress, ospfPort);

                                final ServerBootstrap bootstrap = createServerBootStrap();
                                bootstrap.setOption("reuseAddr", true);
                                bootstrap.setOption("child.keepAlive", true);
                                bootstrap.setOption("child.tcpNoDelay", true);
                                bootstrap.setOption("child.sendBufferSize", Controller.BUFFER_SIZE);

                                //Set the interface name in ospfInterface
                                ospfIf.setInterfaceName(netInt.getDisplayName());
                                //netInt.get
                                // passing OSPFArea and interface to pipelinefactory
                                ChannelPipelineFactory pfact = new OSPFPipelineFactory(this, null, area,
                                        ospfIf);
                                bootstrap.setPipelineFactory(pfact);
                                InetSocketAddress sa = new InetSocketAddress(InetAddress.getByName(ipAddress),
                                        ospfPort);

                                cg = new DefaultChannelGroup();
                                cg.add(bootstrap.bind(sa));

                                log.debug("Listening for connections on {}", sa);
                                //For testing. remove this
                                interfc = ospfIf;

                                //Start aging process
                                area.initializeDB();
                                area.initializeArea();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("Error::Controller:: {}", e.getMessage());
    }
}

From source file:org.openhab.binding.russound.internal.discovery.RioSystemDiscovery.java

/**
 * Starts the scan. For each network interface (that is up and not a loopback), all addresses will be iterated
 * and checked for something open on port 9621. If that port is open, a russound controller "type" command will be
 * issued. If the response is a correct pattern, we assume it's a rio system device and will emit a
 * {{@link #thingDiscovered(DiscoveryResult)}
 *///from ww w. ja v a2  s  .com
@Override
protected void startScan() {
    final List<NetworkInterface> interfaces;
    try {
        interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    } catch (SocketException e1) {
        logger.debug("Exception getting network interfaces: {}", e1.getMessage(), e1);
        return;
    }

    nbrNetworkInterfacesScanning = interfaces.size();
    executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10);

    for (final NetworkInterface networkInterface : interfaces) {
        try {
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
        } catch (SocketException e) {
            continue;
        }

        for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it
                .hasNext();) {
            final InterfaceAddress interfaceAddress = it.next();

            // don't bother with ipv6 addresses (russound doesn't support)
            if (interfaceAddress.getAddress() instanceof Inet6Address) {
                continue;
            }

            final String subnetRange = interfaceAddress.getAddress().getHostAddress() + "/"
                    + interfaceAddress.getNetworkPrefixLength();

            logger.debug("Scanning subnet: {}", subnetRange);
            final SubnetUtils utils = new SubnetUtils(subnetRange);

            final String[] addresses = utils.getInfo().getAllAddresses();

            for (final String address : addresses) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        scanAddress(address);
                    }
                });
            }
        }
    }

    // Finishes the scan and cleans up
    stopScan();
}

From source file:edu.ucsb.eucalyptus.ic.WalrusReplyQueue.java

public void handle(ExceptionMessage muleMsg) {
    try {//from  ww  w .j  av a  2  s. 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:org.apache.geode.internal.net.SocketCreator.java

/**
 * returns a set of the non-loopback InetAddresses for this machine
 */// w  w  w.j  a  va 2 s  .  co  m
public static Set<InetAddress> getMyAddresses() {
    Set<InetAddress> result = new HashSet<InetAddress>();
    Set<InetAddress> locals = new HashSet<InetAddress>();
    Enumeration<NetworkInterface> interfaces;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        throw new IllegalArgumentException(
                LocalizedStrings.StartupMessage_UNABLE_TO_EXAMINE_NETWORK_INTERFACES.toLocalizedString(), e);
    }
    while (interfaces.hasMoreElements()) {
        NetworkInterface face = interfaces.nextElement();
        boolean faceIsUp = false;
        try {
            faceIsUp = face.isUp();
        } catch (SocketException e) {
            InternalDistributedSystem ids = InternalDistributedSystem.getAnyInstance();
            if (ids != null) {
                logger.info("Failed to check if network interface is up. Skipping {}", face, e);
            }
        }
        if (faceIsUp) {
            Enumeration<InetAddress> addrs = face.getInetAddresses();
            while (addrs.hasMoreElements()) {
                InetAddress addr = addrs.nextElement();
                if (addr.isLoopbackAddress() || addr.isAnyLocalAddress()
                        || (!useLinkLocalAddresses && addr.isLinkLocalAddress())) {
                    locals.add(addr);
                } else {
                    result.add(addr);
                }
            } // while
        }
    } // while
      // fix for bug #42427 - allow product to run on a standalone box by using
      // local addresses if there are no non-local addresses available
    if (result.size() == 0) {
        return locals;
    } else {
        return result;
    }
}

From source file:org.openhab.binding.harmonyhub.discovery.HarmonyHubDiscovery.java

/**
 * Send broadcast message over all active interfaces
 *
 * @param discoverString//from   ww w .j  a v a2 s .c  o m
 *            String to be used for the discovery
 */
private void sendDiscoveryMessage(String discoverString) {
    DatagramSocket bcSend = null;
    try {
        bcSend = new DatagramSocket();
        bcSend.setBroadcast(true);

        byte[] sendData = discoverString.getBytes();

        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress[] broadcast = null;

                if (StringUtils.isNotBlank(optionalHost)) {
                    try {
                        broadcast = new InetAddress[] { InetAddress.getByName(optionalHost) };
                    } catch (Exception e) {
                        logger.error("Could not use host for hub discovery", e);
                        return;
                    }
                } else {
                    broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"),
                            InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() };
                }

                for (InetAddress bc : broadcast) {
                    // Send the broadcast package!
                    if (bc != null) {
                        try {
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc,
                                    DISCO_PORT);
                            bcSend.send(sendPacket);
                        } catch (IOException e) {
                            logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
                        } catch (Exception e) {
                            logger.debug(e.getMessage(), e);
                        }
                        logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(),
                                networkInterface.getDisplayName());
                    }
                }
            }
        }

    } catch (IOException e) {
        logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
    } finally {
        try {
            if (bcSend != null) {
                bcSend.close();
            }
        } catch (Exception e) {
            // Ignore
        }
    }

}