List of usage examples for java.net InetAddress isLoopbackAddress
public boolean isLoopbackAddress()
From source file:org.opennms.netmgt.provision.service.vmware.VmwareRequisitionUrlConnection.java
/** * Creates a requisition node for the given managed entity and type. * * @param ipAddresses the set of Ip addresses * @param managedEntity the managed entity * @return the generated requisition node *//* ww w . j a va 2 s. c o m*/ private RequisitionNode createRequisitionNode(Set<String> ipAddresses, ManagedEntity managedEntity, int apiVersion, VmwareViJavaAccess vmwareViJavaAccess) { RequisitionNode requisitionNode = new RequisitionNode(); // Setting the node label requisitionNode.setNodeLabel(managedEntity.getName()); // Foreign Id consisting of managed entity Id requisitionNode.setForeignId(managedEntity.getMOR().getVal()); /* * Original version: * * Foreign Id consisting of VMware management server's hostname and managed entity id * * requisitionNode.setForeignId(m_hostname + "/" + managedEntity.getMOR().getVal()); */ if (managedEntity instanceof VirtualMachine) { boolean firstInterface = true; // add all given interfaces for (String ipAddress : ipAddresses) { try { if ((m_persistIPv4 && InetAddressUtils.isIPv4Address(ipAddress)) || (m_persistIPv6 && InetAddressUtils.isIPv6Address(ipAddress))) { InetAddress inetAddress = InetAddress.getByName(ipAddress); if (!inetAddress.isLoopbackAddress()) { RequisitionInterface requisitionInterface = new RequisitionInterface(); requisitionInterface.setIpAddr(ipAddress); // the first one will be primary if (firstInterface) { requisitionInterface.setSnmpPrimary(PrimaryType.PRIMARY); for (String service : m_virtualMachineServices) { requisitionInterface.insertMonitoredService( new RequisitionMonitoredService(service.trim())); } firstInterface = false; } else { requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY); } requisitionInterface.setManaged(Boolean.TRUE); requisitionInterface.setStatus(Integer.valueOf(1)); requisitionNode.putInterface(requisitionInterface); } } } catch (UnknownHostException unknownHostException) { logger.warn("Invalid IP address '{}'", unknownHostException.getMessage()); } } } else { if (managedEntity instanceof HostSystem) { boolean reachableInterfaceFound = false, firstInterface = true; List<RequisitionInterface> requisitionInterfaceList = new ArrayList<RequisitionInterface>(); RequisitionInterface primaryInterfaceCandidate = null; // add all given interfaces for (String ipAddress : ipAddresses) { try { if ((m_persistIPv4 && InetAddressUtils.isIPv4Address(ipAddress)) || (m_persistIPv6 && InetAddressUtils.isIPv6Address(ipAddress))) { InetAddress inetAddress = InetAddress.getByName(ipAddress); if (!inetAddress.isLoopbackAddress()) { RequisitionInterface requisitionInterface = new RequisitionInterface(); requisitionInterface.setIpAddr(ipAddress); if (firstInterface) { primaryInterfaceCandidate = requisitionInterface; firstInterface = false; } if (!reachableInterfaceFound && reachableCimService(vmwareViJavaAccess, (HostSystem) managedEntity, ipAddress)) { primaryInterfaceCandidate = requisitionInterface; reachableInterfaceFound = true; } requisitionInterface.setManaged(Boolean.TRUE); requisitionInterface.setStatus(Integer.valueOf(1)); requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY); requisitionInterfaceList.add(requisitionInterface); } } } catch (UnknownHostException unknownHostException) { logger.warn("Invalid IP address '{}'", unknownHostException.getMessage()); } } if (primaryInterfaceCandidate != null) { if (reachableInterfaceFound) { logger.warn("Found reachable primary interface '{}'", primaryInterfaceCandidate.getIpAddr()); } else { logger.warn( "Only non-reachable interfaces found, using first one for primary interface '{}'", primaryInterfaceCandidate.getIpAddr()); } primaryInterfaceCandidate.setSnmpPrimary(PrimaryType.PRIMARY); for (String service : m_hostSystemServices) { if (reachableInterfaceFound || !"VMwareCim-HostSystem".equals(service)) { primaryInterfaceCandidate .insertMonitoredService(new RequisitionMonitoredService(service.trim())); } } } else { logger.warn("No primary interface found"); } for (RequisitionInterface requisitionInterface : requisitionInterfaceList) { requisitionNode.putInterface(requisitionInterface); } } else { logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType()); return null; } } /* * For now we use displaycategory, notifycategory and pollercategory for storing * the vcenter Ip address, the username and the password */ String powerState = "unknown"; StringBuffer vmwareTopologyInfo = new StringBuffer(); // putting parents to topology information ManagedEntity parentEntity = managedEntity.getParent(); do { if (vmwareTopologyInfo.length() > 0) { vmwareTopologyInfo.append(", "); } try { if (parentEntity != null && parentEntity.getMOR() != null) { vmwareTopologyInfo.append(parentEntity.getMOR().getVal() + "/" + URLEncoder.encode(parentEntity.getName(), "UTF-8")); } else { logger.warn( "Can't add topologyInformation because either the parentEntity or the MOR is null for " + managedEntity.getName()); } } catch (UnsupportedEncodingException e) { logger.warn("Unsupported encoding '{}'", e.getMessage()); } parentEntity = parentEntity == null ? null : parentEntity.getParent(); } while (parentEntity != null); if (managedEntity instanceof HostSystem) { HostSystem hostSystem = (HostSystem) managedEntity; HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime(); if (hostRuntimeInfo == null) { logger.debug("hostRuntimeInfo=null"); } else { HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState(); if (hostSystemPowerState == null) { logger.debug("hostSystemPowerState=null"); } else { powerState = hostSystemPowerState.toString(); } } try { if (m_topologyDatastores) { for (Datastore datastore : hostSystem.getDatastores()) { if (vmwareTopologyInfo.length() > 0) { vmwareTopologyInfo.append(", "); } try { vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/" + URLEncoder.encode(datastore.getSummary().getName(), "UTF-8")); } catch (UnsupportedEncodingException e) { logger.warn("Unsupported encoding '{}'", e.getMessage()); } } } } catch (RemoteException e) { logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage()); } try { if (m_topologyNetworks) { for (Network network : hostSystem.getNetworks()) { if (vmwareTopologyInfo.length() > 0) { vmwareTopologyInfo.append(", "); } try { if (network instanceof DistributedVirtualPortgroup ? m_topologyPortGroups : true) { vmwareTopologyInfo.append(network.getMOR().getVal() + "/" + URLEncoder.encode(network.getSummary().getName(), "UTF-8")); } } catch (UnsupportedEncodingException e) { logger.warn("Unsupported encoding '{}'", e.getMessage()); } } } } catch (RemoteException e) { logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage()); } } else { if (managedEntity instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) managedEntity; VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime(); if (virtualMachineRuntimeInfo == null) { logger.debug("virtualMachineRuntimeInfo=null"); } else { VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState(); if (virtualMachinePowerState == null) { logger.debug("virtualMachinePowerState=null"); } else { powerState = virtualMachinePowerState.toString(); } } try { if (m_topologyDatastores) { for (Datastore datastore : virtualMachine.getDatastores()) { if (vmwareTopologyInfo.length() > 0) { vmwareTopologyInfo.append(", "); } try { vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/" + URLEncoder.encode(datastore.getSummary().getName(), "UTF-8")); } catch (UnsupportedEncodingException e) { logger.warn("Unsupported encoding '{}'", e.getMessage()); } } } } catch (RemoteException e) { logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage()); } try { if (m_topologyNetworks) { for (Network network : virtualMachine.getNetworks()) { if (vmwareTopologyInfo.length() > 0) { vmwareTopologyInfo.append(", "); } try { if (network instanceof DistributedVirtualPortgroup ? m_topologyPortGroups : true) { vmwareTopologyInfo.append(network.getMOR().getVal() + "/" + URLEncoder.encode(network.getSummary().getName(), "UTF-8")); } } catch (UnsupportedEncodingException e) { logger.warn("Unsupported encoding '{}'", e.getMessage()); } } } } catch (RemoteException e) { logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage()); } if (vmwareTopologyInfo.length() > 0) { vmwareTopologyInfo.append(", "); } try { vmwareTopologyInfo.append(virtualMachine.getRuntime().getHost().getVal() + "/" + URLEncoder .encode(m_hostSystemMap.get(virtualMachine.getRuntime().getHost().getVal()), "UTF-8")); } catch (UnsupportedEncodingException e) { logger.warn("Unsupported encoding '{}'", e.getMessage()); } } else { logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType()); return null; } } RequisitionAsset requisitionAssetHostname = new RequisitionAsset("vmwareManagementServer", m_hostname); requisitionNode.putAsset(requisitionAssetHostname); RequisitionAsset requisitionAssetType = new RequisitionAsset("vmwareManagedEntityType", (managedEntity instanceof HostSystem ? "HostSystem" : "VirtualMachine")); requisitionNode.putAsset(requisitionAssetType); RequisitionAsset requisitionAssetId = new RequisitionAsset("vmwareManagedObjectId", managedEntity.getMOR().getVal()); requisitionNode.putAsset(requisitionAssetId); RequisitionAsset requisitionAssetTopologyInfo = new RequisitionAsset("vmwareTopologyInfo", vmwareTopologyInfo.toString()); requisitionNode.putAsset(requisitionAssetTopologyInfo); RequisitionAsset requisitionAssetState = new RequisitionAsset("vmwareState", powerState); requisitionNode.putAsset(requisitionAssetState); requisitionNode.putCategory(new RequisitionCategory("VMware" + apiVersion)); return requisitionNode; }
From source file:com.vuze.plugin.azVPN_Air.Checker.java
private int findBindingAddress(StringBuilder sReply) { int newStatusID = -1; // Find our VPN binding (interface) address. Checking UDP is the best bet, // since TCP and http might be proxied List<PRUDPPacketHandler> handlers = PRUDPPacketHandlerFactory.getHandlers(); if (handlers.size() == 0) { PRUDPReleasablePacketHandler releasableHandler = PRUDPPacketHandlerFactory.getReleasableHandler(0); handlers = PRUDPPacketHandlerFactory.getHandlers(); releasableHandler.release();/*from ww w . j av a 2s . c o m*/ } if (handlers.size() == 0) { addLiteralReply(sReply, CHAR_BAD + " No UDP Handlers"); newStatusID = STATUS_ID_BAD; } else { InetAddress bindIP = handlers.get(0).getBindIP(); // The "Any" field is equivalent to 0.0.0.0 in dotted-quad notation, which is unbound. // "Loopback" is 127.0.0.1, which is bound when Vuze can't bind to // user specified interface (ie. kill switched) if (bindIP.isAnyLocalAddress() || bindIP.isLoopbackAddress()) { newStatusID = handleUnboundOrLoopback(bindIP, sReply); if (newStatusID == STATUS_ID_BAD) { return newStatusID; } } else { newStatusID = handleBound(bindIP, sReply); } } return newStatusID; }
From source file:net.spfbl.core.Core.java
private static boolean isRouteable(String hostame) { try {//from ww w.j a va2 s. co m Attributes attributesA = Server.getAttributesDNS(hostame, new String[] { "A" }); Attribute attributeA = attributesA.get("A"); if (attributeA == null) { Attributes attributesAAAA = Server.getAttributesDNS(hostame, new String[] { "AAAA" }); Attribute attributeAAAA = attributesAAAA.get("AAAA"); if (attributeAAAA != null) { for (int i = 0; i < attributeAAAA.size(); i++) { String host6Address = (String) attributeAAAA.get(i); if (SubnetIPv6.isValidIPv6(host6Address)) { try { InetAddress address = InetAddress.getByName(host6Address); if (address.isLinkLocalAddress()) { return false; } else if (address.isLoopbackAddress()) { return false; } } catch (UnknownHostException ex) { } } else { return false; } } } } else { for (int i = 0; i < attributeA.size(); i++) { String host4Address = (String) attributeA.get(i); host4Address = host4Address.trim(); if (SubnetIPv4.isValidIPv4(host4Address)) { try { InetAddress address = InetAddress.getByName(host4Address); if (address.isLinkLocalAddress()) { return false; } else if (address.isLoopbackAddress()) { return false; } } catch (UnknownHostException ex) { } } else { return false; } } } return true; } catch (NamingException ex) { return false; } }
From source file:android_network.hetnet.vpn_service.ActivitySettings.java
private void checkAddress(String address) throws IllegalArgumentException, UnknownHostException { if (address == null || TextUtils.isEmpty(address.trim())) throw new IllegalArgumentException("Bad address"); if (!Util.isNumericAddress(address)) throw new IllegalArgumentException("Bad address"); InetAddress idns = InetAddress.getByName(address); if (idns.isLoopbackAddress() || idns.isAnyLocalAddress()) throw new IllegalArgumentException("Bad address"); }
From source file:com.mirth.connect.connectors.tcp.TcpReceiver.java
private void createServerSocket() throws IOException { // Create the server socket int backlog = DEFAULT_BACKLOG; String host = getLocalAddress(); int port = getLocalPort(); InetAddress hostAddress = InetAddress.getByName(host); int bindAttempts = 0; boolean success = false; // If an error occurred during binding, try again. If the JVM fails to bind ten times, throw the exception. while (!success) { try {/* ww w .j a v a 2 s . c o m*/ bindAttempts++; boolean isLoopback = false; try { isLoopback = (hostAddress.isLoopbackAddress() || host.trim().equals("localhost") || hostAddress.equals(InetAddress.getLocalHost())); } catch (UnknownHostException e) { logger.warn("Failed to determine if '" + hostAddress.getHostAddress() + "' is a loopback address. Could not resolve the system's host name to an address.", e); } if (isLoopback) { serverSocket = configuration.createServerSocket(port, backlog); } else { serverSocket = configuration.createServerSocket(port, backlog, hostAddress); } success = true; } catch (BindException e) { if (bindAttempts >= 10) { throw e; } else { try { Thread.sleep(1000); } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } } } }
From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java
public static List<InetAddress> getDns(Context context) { List<InetAddress> listDns = new ArrayList<>(); List<String> sysDns = Util.getDefaultDNS(context); // Get custom DNS servers SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String vpnDns1 = prefs.getString("dns", null); String vpnDns2 = prefs.getString("dns2", null); Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2); if (vpnDns1 != null) try {//from www.j ava 2 s. c om InetAddress dns = InetAddress.getByName(vpnDns1); if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress())) listDns.add(dns); } catch (Throwable ignored) { } if (vpnDns2 != null) try { InetAddress dns = InetAddress.getByName(vpnDns2); if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress())) listDns.add(dns); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } // Use system DNS servers only when no two custom DNS servers specified if (listDns.size() <= 1) for (String def_dns : sysDns) try { InetAddress ddns = InetAddress.getByName(def_dns); if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress())) listDns.add(ddns); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } // Remove local DNS servers when not routing LAN boolean lan = prefs.getBoolean("lan", false); if (lan) { List<InetAddress> listLocal = new ArrayList<>(); try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); if (nis != null) while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); if (ni != null && ni.isUp() && !ni.isLoopback()) { List<InterfaceAddress> ias = ni.getInterfaceAddresses(); if (ias != null) for (InterfaceAddress ia : ias) { InetAddress hostAddress = ia.getAddress(); BigInteger host = new BigInteger(1, hostAddress.getAddress()); int prefix = ia.getNetworkPrefixLength(); BigInteger mask = BigInteger.valueOf(-1) .shiftLeft(hostAddress.getAddress().length * 8 - prefix); for (InetAddress dns : listDns) if (hostAddress.getAddress().length == dns.getAddress().length) { BigInteger ip = new BigInteger(1, dns.getAddress()); if (host.and(mask).equals(ip.and(mask))) { Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix + " dns=" + dns); listLocal.add(dns); } } } } } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } List<InetAddress> listDns4 = new ArrayList<>(); List<InetAddress> listDns6 = new ArrayList<>(); try { listDns4.add(InetAddress.getByName("8.8.8.8")); listDns4.add(InetAddress.getByName("8.8.4.4")); listDns6.add(InetAddress.getByName("2001:4860:4860::8888")); listDns6.add(InetAddress.getByName("2001:4860:4860::8844")); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } for (InetAddress dns : listLocal) { listDns.remove(dns); if (dns instanceof Inet4Address) { if (listDns4.size() > 0) { listDns.add(listDns4.get(0)); listDns4.remove(0); } } else { if (listDns6.size() > 0) { listDns.add(listDns6.get(0)); listDns6.remove(0); } } } } // Prefer IPv4 addresses Collections.sort(listDns, new Comparator<InetAddress>() { @Override public int compare(InetAddress a, InetAddress b) { boolean a4 = (a instanceof Inet4Address); boolean b4 = (b instanceof Inet4Address); if (a4 && !b4) return -1; else if (!a4 && b4) return 1; else return 0; } }); return listDns; }
From source file:org.blue.star.plugins.check_ping.java
public boolean execute_check() { for (String hostname : addresses) { try {/* w w w . j a v a 2s . c o m*/ InetAddress inet = InetAddress.getByName(hostname); long execute_time = 0; long packet_loss = 0; for (int pings = 0; pings < max_packets; pings++) { boolean reachable = false; long ping_time = System.currentTimeMillis(); if (network_interface != null) { reachable = inet.isReachable(network_interface, 0, utils_h.timeout_interval); } else { reachable = inet.isReachable(utils_h.timeout_interval); } execute_time += (System.currentTimeMillis() - ping_time); if (!reachable) packet_loss++; } rta = execute_time / max_packets; pl = (int) packet_loss / max_packets * 100; if (verbose > 0) { System.out.println("rta = " + rta); System.out.println("pl = " + pl); } if (verbose > 1) { System.out.println("isAnyLocalAddress = " + inet.isAnyLocalAddress()); System.out.println("isLinkLocalAddress = " + inet.isLinkLocalAddress()); System.out.println("isLoopbackAddress = " + inet.isLoopbackAddress()); System.out.println("isMCGlobal = " + inet.isMCGlobal()); System.out.println("isMCLinkLocal = " + inet.isMCLinkLocal()); System.out.println("isMCNodeLocal = " + inet.isMCNodeLocal()); System.out.println("isMCOrgLocal = " + inet.isMCOrgLocal()); System.out.println("isMCSiteLocal = " + inet.isMCSiteLocal()); System.out.println("isMulticastAddress = " + inet.isMulticastAddress()); System.out.println("isSiteLocalAddress = " + inet.isSiteLocalAddress()); System.out.println("isReachable = " + inet.isReachable(utils_h.timeout_interval)); System.out.println("getCanonicalHostName = " + inet.getCanonicalHostName()); System.out.println("getHostAddress = " + inet.getHostAddress()); System.out.println("getHostName = " + inet.getHostName()); System.out.println("getClass.getName = " + inet.getClass().getName()); } /* The list is only used to check alternatives, if we pass don't do more */ if (packet_loss != max_packets) break; } catch (Exception e) { warn_text = e.getMessage(); e.printStackTrace(); } } if (pl >= cpl || rta >= crta || rta < 0) check_state = common_h.STATE_CRITICAL; else if (pl >= wpl || rta >= wrta) check_state = common_h.STATE_WARNING; else if (pl >= 0 && rta >= 0) check_state = common_h.STATE_OK; return true; }
From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java
/** * ?IP?./* w w w . j ava 2 s . c o m*/ * * @return ?IP */ public String getLocalIpAddress() { try { 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() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) { String ipAddr = inetAddress.getHostAddress(); return ipAddr; } } } } catch (Exception e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } return null; }
From source file:com.httrack.android.HTTrackActivity.java
/** * Return the IPv6 address.//from w ww . j a va2 s . co m * * @return The ipv6 address, or @c null if no IPv6 connectivity is available. */ protected static InetAddress getIPv6Address() { try { for (final Enumeration<NetworkInterface> interfaces = NetworkInterface .getNetworkInterfaces(); interfaces.hasMoreElements();) { final NetworkInterface iface = interfaces.nextElement(); for (final Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses .hasMoreElements();) { final InetAddress address = addresses.nextElement(); Log.d(HTTrackActivity.class.getSimpleName(), "seen interface: " + address.toString()); if (address instanceof Inet6Address) { if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && !address.isSiteLocalAddress() && !address.isMulticastAddress()) { return address; } } } } } catch (final SocketException se) { Log.w(HTTrackActivity.class.getSimpleName(), "could not enumerate interfaces", se); } return null; }