List of usage examples for java.net NetworkInterface isLoopback
public boolean isLoopback() throws SocketException
From source file:org.openhab.binding.plclogo.internal.discovery.PLCDiscoveryService.java
@Override protected void startScan() { stopScan();/* ww w . j a va 2s . com*/ 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:org.openhab.binding.zway.internal.discovery.ZWayBridgeDiscoveryService.java
private void scan() { logger.debug("Starting scan for Z-Way Server"); ValidateIPV4 validator = new ValidateIPV4(); try {//from ww w . jav a 2 s . co m Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces(); while (enumNetworkInterface.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterface.nextElement(); if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) { for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (validator.isValidIPV4(address.getAddress().getHostAddress())) { String ipAddress = address.getAddress().getHostAddress(); Short prefix = address.getNetworkPrefixLength(); logger.debug("Scan IP address for Z-Way Server: {}", ipAddress); // Search on localhost first scheduler.execute(new ZWayServerScan(ipAddress)); String subnet = ipAddress + "/" + prefix; SubnetUtils utils = new SubnetUtils(subnet); String[] addresses = utils.getInfo().getAllAddresses(); for (String addressInSubnet : addresses) { scheduler.execute(new ZWayServerScan(addressInSubnet)); } } } } } } catch (SocketException e) { logger.warn("Error occurred while searching Z-Way servers ({})", e.getMessage()); } }
From source file:org.openhab.binding.networkhealth.discovery.NetworkHealthDiscoveryService.java
/** * Gets every IPv4 Address on each Interface except the loopback * The Address format is ip/subnet//from w w w. j a v a 2s . co m * @return The collected IPv4 Addresses */ private 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:org.openhab.binding.vera.internal.discovery.VeraBridgeDiscoveryService.java
private void scan() { logger.debug("Starting scan for Vera controller"); ValidateIPV4 validator = new ValidateIPV4(); try {//from ww w.jav a 2 s . com Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces(); while (enumNetworkInterface.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterface.nextElement(); if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) { for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (validator.isValidIPV4(address.getAddress().getHostAddress())) { String ipAddress = address.getAddress().getHostAddress(); Short prefix = address.getNetworkPrefixLength(); logger.debug("Scan IP address for Vera Controller: {}", ipAddress); String subnet = ipAddress + "/" + prefix; SubnetUtils utils = new SubnetUtils(subnet); String[] addresses = utils.getInfo().getAllAddresses(); for (String addressInSubnet : addresses) { scheduler.execute(new VeraControllerScan(addressInSubnet)); } } } } } } catch (SocketException e) { logger.warn("Error occurred while searching Vera controller: ", e); } }
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 w w .j a va2 s . c om*/ 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.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 w w w . j a va2 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 {// w w w . ja va2s . co 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.openhab.binding.network.internal.utils.NetworkUtils.java
/** * Get a set of all interface names.//from www. jav a2 s . c o m * * @return Set of interface names */ public Set<String> getInterfaceNames() { Set<String> result = new HashSet<>(); try { // For each interface ... for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface networkInterface = en.nextElement(); if (!networkInterface.isLoopback()) { result.add(networkInterface.getName()); } } } catch (SocketException ignored) { // If we are not allowed to enumerate, we return an empty result set. } return result; }
From source file:org.onosproject.ospf.controller.impl.Controller.java
/** * Tell controller that we're ready to handle channels. *//* ww w. jav a 2s .co m*/ 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.harmonyhub.discovery.HarmonyHubDiscovery.java
/** * Send broadcast message over all active interfaces * * @param discoverString/*from w w w.ja v a 2 s. co 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 } } }