Example usage for org.apache.http.conn.util InetAddressUtils isIPv4Address

List of usage examples for org.apache.http.conn.util InetAddressUtils isIPv4Address

Introduction

In this page you can find the example usage for org.apache.http.conn.util InetAddressUtils isIPv4Address.

Prototype

public static boolean isIPv4Address(final String input) 

Source Link

Document

Checks whether the parameter is a valid IPv4 address

Usage

From source file:be.deadba.ampd.SettingsActivity.java

private static String getLocalIpAddress() {
    try {//from w ww.  j a  v a2 s.  com
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                String hostAddress = inetAddress.getHostAddress();
                if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(hostAddress)) {
                    return hostAddress;
                }
            }
        }
    } catch (Exception ex) {
        Log.e(TAG, ex.toString());
    }
    return null;
}

From source file:de.jaetzold.networking.SimpleServiceDiscovery.java

/**
  * Comma separated List of IP adresses of available network interfaces
  * @param useIPv4/* w w  w  . j  a va  2 s.co  m*/
  * @return
  */
public static String getIPAddress(boolean useIPv4) {

    String addresses = "";
    try {
        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)
                            addresses += sAddr + ", ";
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                            if (delim < 0)
                                addresses += sAddr + ", ";
                            else
                                addresses += sAddr.substring(0, delim) + ", ";
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    if (addresses == null || addresses.length() <= 3)
        return "";
    return addresses.subSequence(0, addresses.length() - 2).toString();
}

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
 *//*from  w w  w  .  j  a  v  a 2s .  com*/
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:org.basdroid.common.NetworkUtils.java

/**
 * Get IP address from first non-localhost interface
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @param useIPv4  true=return ipv4, false=return ipv6
 * @return  address or empty string//from w w  w.j a  v a  2 s  .  c o  m
 */
public static String getIPAddress(String interfaceName, boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
            }
            List<InetAddress> inetAddresses = Collections.list(intf.getInetAddresses());
            for (InetAddress inetAddr : inetAddresses) {
                if (!inetAddr.isLoopbackAddress()) {
                    String address = inetAddr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(address);
                    if (useIPv4) {
                        if (isIPv4) {
                            return address;
                        }
                    } else {
                        if (!isIPv4) {
                            int delim = address.indexOf('%'); // drop ip6 port suffix
                            return delim < 0 ? address : address.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

From source file:com.terremark.impl.AbstractAPIImpl.java

/**
 * Validates the query arguments against the metadata. {@link java.lang.IllegalArgumentException} is thrown if the
 * arguments does not match the metadata information.
 *
 * @param filterArguments Query arguments. Can be null.
 * @param metadata Metadata for the query arguments.
 *///from  ww w .ja  v  a2 s. c o  m
@SuppressWarnings({ "unused", "PMD.AvoidInstantiatingObjectsInLoops", "PMD.AvoidDuplicateLiterals" })
protected static void validateQueryArguments(final Map<String, String> filterArguments,
        final Map<String, QueryArgument> metadata) {
    if (filterArguments == null) {
        return;
    }

    for (Map.Entry<String, String> entry : filterArguments.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        if (key == null) {
            throw new IllegalArgumentException("Invalid filter argument key");
        }
        if (StringUtils.isEmpty(value)) {
            throw new IllegalArgumentException("Invalid filter argument value for " + key);
        }

        final QueryArgument argInfo = metadata.get(key);
        if (argInfo == null) {
            throw new IllegalArgumentException("Invalid filter argument: " + key);
        }

        switch (argInfo.getType()) {
        case INTEGER:
            int i;
            try {
                i = Integer.parseInt(value);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value
                        + ". Must be a valid integer", ex);
            }

            if (argInfo.getMinValue() != Integer.MAX_VALUE && argInfo.getMaxValue() != Integer.MIN_VALUE
                    && (i < argInfo.getMinValue() || i > argInfo.getMaxValue())) {
                throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value
                        + ". It should be between " + argInfo.getMinValue() + " and " + argInfo.getMaxValue());
            }
            break;
        case LIST:
            boolean found = false;
            for (String str : argInfo.getArgs()) {
                if (value.equalsIgnoreCase(str)) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value
                        + ". It should be one of: " + Arrays.asList(argInfo.getArgs()));
            }
            break;
        case ISO8601_DATE:
            final SimpleDateFormat sdf = new SimpleDateFormat(TerremarkConstants.ISO_8601_DATE_FORMAT,
                    Locale.getDefault());
            try {
                sdf.parse(value);
            } catch (ParseException ex) {
                throw new IllegalArgumentException(
                        "Invalid filter argument value for '" + key + "': " + value
                                + ". Must be a valid date/time in ISO 8601 format: yyyy-MM-dd'T'HH:mm:'00Z'",
                        ex);
            }
            break;
        case HOSTNAME:
            try {
                InetAddress.getByName(value);
            } catch (UnknownHostException ex) {
                throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value
                        + ". Must be a valid hostname/IP address", ex);
            }
            break;
        case IP_ADDRESS:
            if (!InetAddressUtils.isIPv4Address(value)) {
                throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value
                        + ". Must be a valid IPv4 address");
            }
            break;
        case SUBNET:
            new SubnetUtils(value);
            break;
        case URI:
            try {
                new URI(value);
            } catch (URISyntaxException ex) {
                throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value
                        + ". Must be a valid relative URI", ex);
            }
            break;
        default:
            break;
        }
    }
}

From source file:com.carreygroup.JARVIS.Demon.java

/**
 * Get IP address from first non-localhost interface
 * @param ipv4  true=return ipv4, false=return ipv6
 * @return  address or empty string// w ww  .  ja va 2  s . co  m
 */
public static String getLoaclIPAddress(boolean useIPv4) {
    try {
        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:uk.org.openseizuredetector.MainActivity.java

/** get the ip address of the phone.
 * Based on http://stackoverflow.com/questions/11015912/how-do-i-get-ip-address-in-ipv4-format
 *///  w  w w .j  a v a2 s .c o m
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();
                //Log.v(TAG,"ip1--:" + inetAddress);
                //Log.v(TAG,"ip2--:" + inetAddress.getHostAddress());

                // for getting IPV4 format
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {

                    String ip = inetAddress.getHostAddress().toString();
                    //Log.v(TAG,"ip---::" + ip);
                    return ip;
                }
            }
        }
    } catch (Exception ex) {
        Log.e("IP Address", ex.toString());
    }
    return null;
}

From source file:com.adamkruger.myipaddressinfo.NetworkInfoFragment.java

private static String InetAddressToString(InetAddress address) {
    String addressString = address.getHostAddress().toUpperCase(Locale.getDefault());
    if (InetAddressUtils.isIPv4Address(addressString)) {
        return addressString;
    } else {//w  w w  . ja va  2 s .c o m
        int suffixPosition = addressString.indexOf('%');
        return suffixPosition < 0 ? addressString : addressString.substring(0, suffixPosition);
    }
}

From source file:com.ibm.stocator.fs.common.Utils.java

public static boolean validContainer(String container) throws InvalidContainerNameException {
    if (container != null && container.length() < 4) {
        throw new InvalidContainerNameException(
                "Container " + container + " length must be at least 3 letters");
    }//from   w w w  .j  a  va 2  s.c o m
    if (InetAddressUtils.isIPv4Address(container)) {
        throw new InvalidContainerNameException("Container " + container + " is of IP address pattern");
    }
    return true;
}