Example usage for java.net InetAddress isMulticastAddress

List of usage examples for java.net InetAddress isMulticastAddress

Introduction

In this page you can find the example usage for java.net InetAddress isMulticastAddress.

Prototype

public boolean isMulticastAddress() 

Source Link

Document

Utility routine to check if the InetAddress is an IP multicast address.

Usage

From source file:ac.dynam.rundeck.plugin.resources.ovirt.InstanceToNodeMapper.java

/**
 * Convert an oVirt Instance to a RunDeck INodeEntry based on the mapping input
 *///ww w . j a va2  s  .co m
@SuppressWarnings("unchecked")
static INodeEntry instanceToNode(final VM inst) throws GeneratorException {
    final NodeEntryImpl node = new NodeEntryImpl();

    node.setNodename(inst.getName());
    node.setOsArch(inst.getCpu().getArchitecture());
    node.setOsName(inst.getOs().getType());
    node.setDescription(inst.getDescription());
    node.setUsername("root");
    InetAddress address = null;
    if (inst.getGuestInfo() != null) {
        try {
            address = InetAddress.getByName(inst.getGuestInfo().getFqdn());
            logger.debug("Host " + node.getNodename() + " Guest FQDN " + inst.getGuestInfo().getFqdn()
                    + " Address: " + address.getHostName());
            if (address.getHostName() == "localhost")
                throw new UnknownHostException();
        } catch (UnknownHostException e) {
            /* try the first IP instead then */
            logger.warn("Host " + node.getNodename() + " address " + inst.getGuestInfo().getFqdn()
                    + " does not resolve. Trying IP addresses instead");
            for (int i = 0; i < inst.getGuestInfo().getIps().getIPs().size(); i++) {
                logger.debug("Host " + node.getNodename() + " Trying "
                        + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                try {
                    address = InetAddress.getByName(inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                    if (address != null) {
                        if (address.isLinkLocalAddress() || address.isMulticastAddress()) {
                            logger.warn("Host " + node.getNodename() + " ip address is not valid: "
                                    + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                            continue;
                        }
                        logger.debug("Host " + node.getNodename() + " ip address " + address.getHostAddress()
                                + " will be used instead");
                        break;
                    }
                } catch (UnknownHostException e1) {
                    logger.warn("Host " + node.getNodename() + " IP Address "
                            + inst.getGuestInfo().getIps().getIPs().get(i).getAddress() + " is invalid");
                }
            }
        }
    }
    if (address == null) {
        /* try resolving based on name */
        try {
            address = InetAddress.getByName(node.getNodename());
        } catch (UnknownHostException e) {
            logger.warn("Unable to Find IP address for Host " + node.getNodename());
            return null;
        }
    }

    if (address != null)
        node.setHostname(address.getCanonicalHostName());

    if (inst.getTags() != null) {
        VMTags tags = inst.getTags();
        final HashSet<String> tagset = new HashSet<String>();
        try {
            for (int j = 0; j < tags.list().size(); j++) {
                tagset.add(tags.list().get(j).getName());
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (null == node.getTags()) {
            node.setTags(tagset);
        } else {
            final HashSet<String> orig = new HashSet<String>(node.getTags());
            orig.addAll(tagset);
            node.setTags(orig);
        }
    }

    if (inst.getHighAvailability().getEnabled())
        node.setAttribute("HighAvailability", "true");
    if (inst.getType() != null)
        node.setAttribute("Host Type", inst.getType());
    node.setAttribute("oVirt VM", "true");
    node.setAttribute("oVirt Host", inst.getHost().getName());

    return node;
}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

/**
 * Constructs a new instance of this class.
 */// w  w w. j  ava2 s.  c o m
private SsdpHandler() {
    LOG.info("Instantiating SsdpHandler");

    try {
        // Use first IPv4 address that isn't loopback, any, or link local as the server address
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && serverAddress == null) {
            NetworkInterface i = interfaces.nextElement();
            Enumeration<InetAddress> addresses = i.getInetAddresses();
            while (addresses.hasMoreElements() && serverAddress == null) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    if (!address.isAnyLocalAddress() && !address.isLinkLocalAddress()
                            && !address.isLoopbackAddress() && !address.isMulticastAddress()) {
                        serverAddress = address;
                    }
                }
            }
        }

        if (serverAddress == null) {
            LOG.warn("Server address unknown");
        }

        svc = SsdpService.forAllMulticastAvailableNetworkInterfaces(this);
        svc.listen();

        // setup Multicast for Notify messages
        notifySocket = new MulticastSocket();
        notifySocket.setTimeToLive(TTL);
        notifyTimer = new Timer("UPnP Notify Timer", true);
        notifyTimer.scheduleAtFixedRate(new NotifySender(), 5000, MAX_AGE * 1000 / 2);
    } catch (Exception e) {
        LOG.error("SsdpHandler in unknown state due to exception in constructor.", e);
    }
}

From source file:com.cloud.storage.template.HttpTemplateDownloader.java

private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException {
    try {/*from   w w w.  j ava2  s.c o  m*/
        URI uri = new URI(url);
        if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) {
            throw new IllegalArgumentException("Unsupported scheme for url");
        }
        int port = uri.getPort();
        if (!(port == 80 || port == 443 || port == -1)) {
            throw new IllegalArgumentException("Only ports 80 and 443 are allowed");
        }

        if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
            port = 443;
        } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
            port = 80;
        }

        String host = uri.getHost();
        try {
            InetAddress hostAddr = InetAddress.getByName(host);
            if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress()
                    || hostAddr.isMulticastAddress()) {
                throw new IllegalArgumentException("Illegal host specified in url");
            }
            if (hostAddr instanceof Inet6Address) {
                throw new IllegalArgumentException(
                        "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
            }
            return new Pair<String, Integer>(host, port);
        } catch (UnknownHostException uhe) {
            throw new IllegalArgumentException("Unable to resolve " + host);
        }
    } catch (IllegalArgumentException iae) {
        s_logger.warn("Failed uri validation check: " + iae.getMessage());
        throw iae;
    } catch (URISyntaxException use) {
        s_logger.warn("Failed uri syntax check: " + use.getMessage());
        throw new IllegalArgumentException(use.getMessage());
    }
}

From source file:org.alfresco.bm.test.Test.java

/**
 * Initialize IP address and hostname/*from   ww w. java 2s . c  o  m*/
 */
private void initNetworkDetails() throws Exception {
    // We have some preferences about what to use
    InetAddress ipv4 = null;
    InetAddress multicast = null;
    InetAddress ipv6 = null;

    // Get an IP address and host name
    Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
    while (nis.hasMoreElements()) {
        NetworkInterface ni = nis.nextElement();
        // Check each network interface
        Enumeration<InetAddress> ias = ni.getInetAddresses();
        while (ias.hasMoreElements()) {
            InetAddress ia = ias.nextElement();
            if (ipv4 == null && ia instanceof Inet4Address) {
                // Our first choice
                ipv4 = ia;
            } else if (multicast != null && ia.isMulticastAddress()) {
                multicast = ia;
            } else if (ipv6 != null && ia instanceof Inet6Address) {
                ipv6 = ia;
            }
        }
    }
    // Now go by preference
    if (ipv4 != null) {
        inetAddress = ipv4;
    } else if (multicast != null) {
        inetAddress = multicast;
    } else if (ipv6 != null) {
        inetAddress = ipv6;
    } else if (inetAddress == null) {
        inetAddress = InetAddress.getLocalHost();
    }
}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getNetworkParams(final NetworkInterface nic) {
    final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }/*from  w  w  w.  j  a v  a2  s.  c o m*/
    InterfaceAddress addr = null;
    for (final InterfaceAddress iaddr : addrs) {
        final InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress()
                && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    final String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        final byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (final SocketException e) {
        s_logger.debug("Caught exception when trying to get the mac address ", e);
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}

From source file:Reflector.java

private InetAddress returnValidMCIP(String IP) {
    // return InetAddress if IP is valid multicast addr,
    // null otherwise

    InetAddress inet = returnValidIP(IP);
    if (inet.isMulticastAddress()) {
        return (inet);
    } else {/*  w  w  w  .ja  va2s  .  c om*/
        return (null);
    }
}

From source file:org.apache.geode.distributed.internal.AbstractDistributionConfig.java

@ConfigAttributeChecker(name = MCAST_ADDRESS)
protected InetAddress checkMcastAddress(InetAddress value) {
    if (!value.isMulticastAddress()) {
        throw new IllegalArgumentException(
                LocalizedStrings.AbstractDistributionConfig_COULD_NOT_SET_0_TO_1_BECAUSE_IT_WAS_NOT_A_MULTICAST_ADDRESS
                        .toLocalizedString(new Object[] { MCAST_ADDRESS, value }));
    }//from w ww .j a va 2s .co m
    return value;
}

From source file:com.httrack.android.HTTrackActivity.java

/**
 * Return the IPv6 address.//from w w w  .  j a  va  2  s  .  com
 * 
 * @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;
}

From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java

/**
 * Will check the configured addresses are reachable and Nuxeo required ports are available on those addresses.
 * Server specific implementations should override this method in order to check for server specific ports.
 * {@link #PARAM_BIND_ADDRESS} must be set before.
 *
 * @throws ConfigurationException//from   w  ww .  j av a 2 s.  c om
 * @since 5.5
 * @see ServerConfigurator#verifyInstallation()
 */
public void checkAddressesAndPorts() throws ConfigurationException {
    InetAddress bindAddress = getBindAddress();
    // Sanity check
    if (bindAddress.isMulticastAddress()) {
        throw new ConfigurationException("Multicast address won't work: " + bindAddress);
    }
    checkAddressReachable(bindAddress);
    checkPortAvailable(bindAddress, Integer.parseInt(userConfig.getProperty(PARAM_HTTP_PORT)));
}

From source file:org.blue.star.plugins.check_ping.java

public boolean execute_check() {

    for (String hostname : addresses) {

        try {/*from  www  .  java 2 s .  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;
}