Java Code Examples for java.net.InetAddress#getClass()

The following examples show how to use java.net.InetAddress#getClass() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AdvancedHostResolverTest.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveIPv4AndIPv6Addresses() {
    assumeTrue("Skipping test because IPv6 is not enabled", ipv6Enabled);

    boolean foundIPv4 = false;
    Collection<InetAddress> addresses = resolver.resolve("www.google.com");
    for (InetAddress address : addresses) {
        if (address.getClass() == Inet4Address.class) {
            foundIPv4 = true;
        }
    }

    assertTrue("Expected to find at least one IPv4 address for www.google.com", foundIPv4);

    // disabling this assert to prevent test failures on systems without ipv6 access, or when the DNS server does not return IPv6 addresses
    //assertTrue("Expected to find at least one IPv6 address for www.google.com", foundIPv6);

}
 
Example 2
Source File: NetworkUtils.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
public static String getLocalIp() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                continue;
            if (iface.getName().startsWith("vboxnet"))
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                final String ip = addr.getHostAddress();
                if (Inet4Address.class == addr.getClass())
                    return ip;
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 3
Source File: UdpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("JdkObsolete")
private boolean isMulticastEnabledIPv4Interface(NetworkInterface iface) {
	try {
		if (!iface.supportsMulticast() || !iface.isUp()) {
			return false;
		}
	}
	catch (SocketException se) {
		return false;
	}

	// Suppressed "JdkObsolete", usage of Enumeration is deliberate
	for (Enumeration<InetAddress> i = iface.getInetAddresses(); i.hasMoreElements(); ) {
		InetAddress address = i.nextElement();
		if (address.getClass() == Inet4Address.class) {
			return true;
		}
	}

	return false;
}
 
Example 4
Source File: CidrAddressBlock.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if the supplied {@link InetAddress} is within
 * this {@code CidrAddressBlock}, {@code false} otherwise.
 *
 * <p>This can be used to test if the argument falls within a well-known
 * network range, a la GoogleIp's isGoogleIp(), isChinaIp(), et alia.
 *
 * @param ipAddr {@link InetAddress} to evaluate.
 * @return {@code true} if {@code ipAddr} is logically within this block,
 *         {@code false} otherwise.
 */
public boolean contains(@Nullable InetAddress ipAddr) {
  if (ipAddr == null) {
    return false;
  }

  // IPv4 CIDR netblocks can never contain IPv6 addresses, and vice versa.
  // Calling getClass() is safe because the Inet4Address and Inet6Address
  // classes are final.
  if (ipAddr.getClass() != ip.getClass()) {
    return false;
  }

  try {
    return ip.equals(applyNetmask(ipAddr, netmask));
  } catch (IllegalArgumentException e) {

    // Something has gone very wrong. This CidrAddressBlock should
    // not have been created with an invalid netmask and a valid
    // netmask should have been successfully applied to "ipAddr" as long
    // as it represents an address of the same family as "this.ip".
    CidrAddressBlockLogger.logger.atWarning().withCause(e).log("Error while applying netmask.");
    return false;
  }
}
 
Example 5
Source File: NetworkUtils.java    From kylin with Apache License 2.0 6 votes vote down vote up
public static String getLocalIp() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                continue;
            if (iface.getName().startsWith("vboxnet"))
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                final String ip = addr.getHostAddress();
                if (Inet4Address.class == addr.getClass())
                    return ip;
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 6
Source File: MiscUtils.java    From RISE-V2G with MIT License 5 votes vote down vote up
/**
 * Determines the link-local IPv6 address which is configured on the network interface provided
 * in the properties file.
 * @return The link-local address given as a String
 */
public static Inet6Address getLinkLocalAddress() {
	String networkInterfaceConfig = getPropertyValue("network.interface").toString();
	
	NetworkInterface nif = null;
	
	try {
		if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
			nif = NetworkInterface.getByIndex(Integer.parseInt(networkInterfaceConfig));
		} else {
			nif = NetworkInterface.getByName(networkInterfaceConfig);
		}
		Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
		
		while (inetAddresses.hasMoreElements()) {
			InetAddress inetAddress = inetAddresses.nextElement();
			
			if (inetAddress.getClass() == Inet6Address.class && inetAddress.isLinkLocalAddress()) {
				return (Inet6Address) inetAddress;
			}
		}
		
		getLogger().fatal("No IPv6 link-local address found on the network interface '" +
				nif.getDisplayName() + "' configured in the properties file");
	} catch (SocketException e) {
		getLogger().fatal("SocketException while trying to get network interface for configured name " +
						  networkInterfaceConfig + "'", e); 
	} catch (NullPointerException | NumberFormatException e2) {
		getLogger().fatal("No network interface for configured network interface index '" + 
						  networkInterfaceConfig + "' found");
	}
	
	return null;
}
 
Example 7
Source File: DatabaseDescriptor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private static InetAddress getNetworkInterfaceAddress(String intf, String configName, boolean preferIPv6) throws ConfigurationException
{
    try
    {
        NetworkInterface ni = NetworkInterface.getByName(intf);
        if (ni == null)
            throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" could not be found");
        Enumeration<InetAddress> addrs = ni.getInetAddresses();
        if (!addrs.hasMoreElements())
            throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" was found, but had no addresses");

        /*
         * Try to return the first address of the preferred type, otherwise return the first address
         */
        InetAddress retval = null;
        while (addrs.hasMoreElements())
        {
            InetAddress temp = addrs.nextElement();
            if (preferIPv6 && temp.getClass() == Inet6Address.class) return temp;
            if (!preferIPv6 && temp.getClass() == Inet4Address.class) return temp;
            if (retval == null) retval = temp;
        }
        return retval;
    }
    catch (SocketException e)
    {
        throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" caused an exception", e);
    }
}
 
Example 8
Source File: InternetAddress.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static InternetAddress from(InetAddress inetAddress) {
    if (inetAddress instanceof Inet4Address) {
        return new InternetAddress.Ipv4(inetAddress.getHostAddress(), (Inet4Address) inetAddress);
    } else if (inetAddress instanceof Inet6Address) {
        return new InternetAddress.Ipv6(inetAddress.getHostAddress(), (Inet6Address) inetAddress);
    } else {
        throw new IllegalArgumentException("Unknown type " + inetAddress.getClass() + " of " + inetAddress);
    }
}
 
Example 9
Source File: DnsNameResolverTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static Map<String, InetAddress> testResolve0(DnsNameResolver resolver, Set<String> excludedDomains,
                                                     DnsRecordType cancelledType)
        throws InterruptedException {

    assertThat(resolver.isRecursionDesired(), is(true));

    final Map<String, InetAddress> results = new HashMap<String, InetAddress>();
    final Map<String, Future<InetAddress>> futures =
            new LinkedHashMap<String, Future<InetAddress>>();

    for (String name : DOMAINS) {
        if (excludedDomains.contains(name)) {
            continue;
        }

        resolve(resolver, futures, name);
    }

    for (Entry<String, Future<InetAddress>> e : futures.entrySet()) {
        String unresolved = e.getKey();
        InetAddress resolved = e.getValue().sync().getNow();

        logger.info("{}: {}", unresolved, resolved.getHostAddress());

        assertThat(resolved.getHostName(), is(unresolved));

        boolean typeMatches = false;
        for (InternetProtocolFamily f: resolver.resolvedInternetProtocolFamiliesUnsafe()) {
            Class<?> resolvedType = resolved.getClass();
            if (f.addressType().isAssignableFrom(resolvedType)) {
                typeMatches = true;
            }
        }

        assertThat(typeMatches, is(true));

        results.put(resolved.getHostName(), resolved);
    }

    assertQueryObserver(resolver, cancelledType);

    return results;
}