public void testTeredoAddress_nullServer() { InetAddresses.TeredoInfo info = new InetAddresses.TeredoInfo(null, null, 80, 1000); assertEquals(InetAddresses.forString("0.0.0.0"), info.getServer()); assertEquals(InetAddresses.forString("0.0.0.0"), info.getClient()); assertEquals(80, info.getPort()); assertEquals(1000, info.getFlags()); }
/** * Returns a {@code HostSpecifier} built from the provided {@code specifier}, which is already * known to be valid. If the {@code specifier} might be invalid, use {@link #from(String)} * instead. * * <p>The specifier must be in one of these formats: * * <ul> * <li>A domain name, like {@code google.com} * <li>A IPv4 address string, like {@code 127.0.0.1} * <li>An IPv6 address string with or without brackets, like {@code [2001:db8::1]} or {@code * 2001:db8::1} * </ul> * * @throws IllegalArgumentException if the specifier is not valid. */ public static HostSpecifier fromValid(String specifier) { // Verify that no port was specified, and strip optional brackets from // IPv6 literals. final HostAndPort parsedHost = HostAndPort.fromString(specifier); Preconditions.checkArgument(!parsedHost.hasPort()); final String host = parsedHost.getHostText(); // Try to interpret the specifier as an IP address. Note we build // the address rather than using the .is* methods because we want to // use InetAddresses.toUriString to convert the result to a string in // canonical form. InetAddress addr = null; try { addr = InetAddresses.forString(host); } catch (IllegalArgumentException e) { // It is not an IPv4 or IPv6 literal } if (addr != null) { return new HostSpecifier(InetAddresses.toUriString(addr)); } // It is not any kind of IP address; must be a domain name or invalid. // TODO(user): different versions of this for different factories? final InternetDomainName domain = InternetDomainName.from(host); if (domain.hasPublicSuffix()) { return new HostSpecifier(domain.name()); } throw new IllegalArgumentException( "Domain name does not have a recognized public suffix: " + host); }
public void testToUriStringIPv6() { // Unfortunately the InetAddress.toString() method for IPv6 addresses // does not collapse contiguous shorts of zeroes with the :: abbreviation. String ipStr = "3ffe::1"; InetAddress ip = InetAddresses.forString(ipStr); assertEquals("[3ffe::1]", InetAddresses.toUriString(ip)); }
public void testForStringIPv6Input() throws UnknownHostException { String ipStr = "3ffe::1"; InetAddress ipv6Addr = null; // Shouldn't hit DNS, because it's an IP string literal. ipv6Addr = InetAddress.getByName(ipStr); assertEquals(ipv6Addr, InetAddresses.forString(ipStr)); assertTrue(InetAddresses.isInetAddress(ipStr)); }
public void test3ff31() { try { InetAddresses.forString("3ffe:::1"); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) { // expected behavior } assertFalse(InetAddresses.isInetAddress("016.016.016.016")); }
public void testConvertDottedQuadToHex() throws UnknownHostException { String[] ipStrings = { "7::0.128.0.127", "7::0.128.0.128", "7::128.128.0.127", "7::0.128.128.127" }; for (String ipString : ipStrings) { // Shouldn't hit DNS, because it's an IP string literal. InetAddress ipv6Addr = InetAddress.getByName(ipString); assertEquals(ipv6Addr, InetAddresses.forString(ipString)); assertTrue(InetAddresses.isInetAddress(ipString)); } }
public void testIsMaximum() throws UnknownHostException { InetAddress address = InetAddress.getByName("255.255.255.254"); assertFalse(InetAddresses.isMaximum(address)); address = InetAddress.getByName("255.255.255.255"); assertTrue(InetAddresses.isMaximum(address)); address = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); assertFalse(InetAddresses.isMaximum(address)); address = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); assertTrue(InetAddresses.isMaximum(address)); }
public void testForStringIPv6EightColons() throws UnknownHostException { String[] eightColons = { "::7:6:5:4:3:2:1", "::7:6:5:4:3:2:0", "7:6:5:4:3:2:1::", "0:6:5:4:3:2:1::", }; for (int i = 0; i < eightColons.length; i++) { InetAddress ipv6Addr = null; // Shouldn't hit DNS, because it's an IP string literal. ipv6Addr = InetAddress.getByName(eightColons[i]); assertEquals(ipv6Addr, InetAddresses.forString(eightColons[i])); assertTrue(InetAddresses.isInetAddress(eightColons[i])); } }
public void testTeredoAddresses() { String[] nonTeredoAddresses = { "::1.2.3.4", "3ffe::1", "::", "::1", }; for (int i = 0; i < nonTeredoAddresses.length; i++) { InetAddress ip = InetAddresses.forString(nonTeredoAddresses[i]); assertFalse(InetAddresses.isTeredoAddress((Inet6Address) ip)); try { InetAddresses.getTeredoInfo((Inet6Address) ip); fail("IllegalArgumentException expected for '" + nonTeredoAddresses[i] + "'"); } catch (IllegalArgumentException expected) { // expected behavior } } String validTeredoAddress = "2001:0000:4136:e378:8000:63bf:3fff:fdd2"; String serverStr = "65.54.227.120"; String clientStr = "192.0.2.45"; int port = 40000; int flags = 0x8000; InetAddress ip = InetAddresses.forString(validTeredoAddress); assertTrue(InetAddresses.isTeredoAddress((Inet6Address) ip)); InetAddresses.TeredoInfo teredo = InetAddresses.getTeredoInfo((Inet6Address) ip); InetAddress server = InetAddresses.forString(serverStr); assertEquals(server, teredo.getServer()); InetAddress client = InetAddresses.forString(clientStr); assertEquals(client, teredo.getClient()); assertEquals(port, teredo.getPort()); assertEquals(flags, teredo.getFlags()); }
/** * Get all predefined all floating IPs defined in cartridge definition. * * @param array of {@link NetworkInterface} * @return list of predefined floating IPs */ public List<String> getAllPredefinedFloatingIPs(NetworkInterface[] networkInterfaces) { String nwInterfacesNullMsg = "Input NetworkInterface array cannot be null"; assertNotNull(networkInterfaces, nwInterfacesNullMsg); List<String> allPredefinedFloatingIPs = new ArrayList<String>(); for (NetworkInterface networkInterface : networkInterfaces) { // if no floating networks defined, skip it if (null == networkInterface.getFloatingNetworks()) { continue; } FloatingNetwork[] floatingNetworks = networkInterface.getFloatingNetworks().getFloatingNetworks(); if (floatingNetworks == null || floatingNetworks.length == 0) { continue; } for (FloatingNetwork floatingNetwork : floatingNetworks) { String floatingIP = floatingNetwork.getFloatingIP(); // we are giving more priority to network uuid over fixed floating IPs // so if both network uuid and floating IPs defined, we are not going to assign those // floating IPs // so these can be assigned to some other interfaces // hence excluding from predefined floating IPs list String networkUuid = floatingNetwork.getNetworkUuid(); if (networkUuid == null || networkUuid.isEmpty()) { if (floatingIP != null && InetAddresses.isInetAddress(floatingIP)) { allPredefinedFloatingIPs.add(floatingIP); } } } } return allPredefinedFloatingIPs; }
private boolean isValid() { if (myUseHTTPProxyRb.isSelected()) { String host = getText(myProxyHostTextField); if (host == null) { return false; } try { HostAndPort parsedHost = HostAndPort.fromString(host); if (parsedHost.hasPort()) { return false; } host = parsedHost.getHostText(); try { InetAddresses.forString(host); return true; } catch (IllegalArgumentException e) { // it is not an IPv4 or IPv6 literal } InternetDomainName.from(host); } catch (IllegalArgumentException e) { return false; } if (myProxyAuthCheckBox.isSelected()) { return !StringUtil.isEmptyOrSpaces(myProxyLoginTextField.getText()) && myProxyPasswordTextField.getPassword().length > 0; } } return true; }
public void testCompatIPv4Addresses() { String[] nonCompatAddresses = { "3ffe::1", "::", "::1", }; for (int i = 0; i < nonCompatAddresses.length; i++) { InetAddress ip = InetAddresses.forString(nonCompatAddresses[i]); assertFalse(InetAddresses.isCompatIPv4Address((Inet6Address) ip)); try { InetAddresses.getCompatIPv4Address((Inet6Address) ip); fail("IllegalArgumentException expected for '" + nonCompatAddresses[i] + "'"); } catch (IllegalArgumentException expected) { // expected behavior } } String[] validCompatAddresses = { "::1.2.3.4", "::102:304", }; String compatStr = "1.2.3.4"; InetAddress compat = InetAddresses.forString(compatStr); for (int i = 0; i < validCompatAddresses.length; i++) { InetAddress ip = InetAddresses.forString(validCompatAddresses[i]); assertTrue("checking '" + validCompatAddresses[i] + "'", ip instanceof Inet6Address); assertTrue( "checking '" + validCompatAddresses[i] + "'", InetAddresses.isCompatIPv4Address((Inet6Address) ip)); assertEquals( "checking '" + validCompatAddresses[i] + "'", compat, InetAddresses.getCompatIPv4Address((Inet6Address) ip)); } }
public void testFromLittleEndianByteArray() throws UnknownHostException { assertEquals( InetAddresses.fromLittleEndianByteArray(new byte[] {1, 2, 3, 4}), InetAddress.getByAddress(new byte[] {4, 3, 2, 1})); assertEquals( InetAddresses.fromLittleEndianByteArray( new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), InetAddress.getByAddress( new byte[] {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})); try { InetAddresses.fromLittleEndianByteArray(new byte[3]); fail("expected exception"); } catch (UnknownHostException expected) { // success } }
@Override public boolean apply(String input) { try { // Note we can do this, as InetAddress is now on the white list return (InetAddresses.forString(input) instanceof Inet4Address); } catch (IllegalArgumentException e) { // could be a hostname return true; } }
/** * Converts an IPv6 string literal (e.g., "1111:2222::8888") into an IP address. * * @param value an IPv6 address value in string form * @return an IPv6 address * @throws IllegalArgumentException if the argument is invalid */ public static Ip6Address valueOf(String value) { InetAddress inetAddress = null; try { inetAddress = InetAddresses.forString(value); } catch (IllegalArgumentException e) { final String msg = "Invalid IP address string: " + value; throw new IllegalArgumentException(msg); } return valueOf(inetAddress); }
public InetAddress getInetAddress() { if (!fields.containsKey("gl2_remote_ip")) { return null; } final String ipAddr = (String) fields.get("gl2_remote_ip"); try { return InetAddresses.forString(ipAddr); } catch (IllegalArgumentException ignored) { return null; } }
private static InetAddress parseInetAddress(String addrStr) { if (addrStr == null || addrStr.isEmpty()) { return null; } try { return InetAddresses.forString(addrStr); } catch (IllegalArgumentException e) { log.error(String.format("Failed to parse Inet address string: %s", addrStr), e); return null; } }
private String getConsumerEndpoint(String endpoint) { if (Strings.isNullOrEmpty(endpoint)) { Optional<InetAddress> address = getOneControlInetAddress(); if (!address.isPresent()) { logger.warn("Could not determine MTOSI/OneControl consumer end point"); return getEndPoint(InetAddresses.forString("127.0.0.1")); } return getEndPoint(address.get()); } return endpoint; }
@Override public IpAddress evaluate(FunctionArgs args, EvaluationContext context) { final String ipString = String.valueOf(ipParam.required(args, context)); try { final InetAddress inetAddress = InetAddresses.forString(ipString); return new IpAddress(inetAddress); } catch (IllegalArgumentException e) { final Optional<String> defaultValue = defaultParam.optional(args, context); if (!defaultValue.isPresent()) { return new IpAddress(ANYV4); } try { return new IpAddress(InetAddresses.forString(defaultValue.get())); } catch (IllegalFormatException e1) { log.warn( "Parameter `default` for to_ip() is not a valid IP address: {}", defaultValue.get()); throw e1; } } }
public void testIncrementIPv6() throws UnknownHostException { InetAddress addressV6_66_0 = InetAddress.getByName("2001:db8::6600"); InetAddress addressV6_66_ff = InetAddress.getByName("2001:db8::66ff"); InetAddress addressV6_67_0 = InetAddress.getByName("2001:db8::6700"); InetAddress address = addressV6_66_0; for (int i = 0; i < 255; i++) { address = InetAddresses.increment(address); } assertEquals(addressV6_66_ff, address); address = InetAddresses.increment(address); assertEquals(addressV6_67_0, address); InetAddress addressV6_ffffff = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); address = addressV6_ffffff; try { address = InetAddresses.increment(address); fail(); } catch (IllegalArgumentException expected) { } }
public void testIncrementIPv4() throws UnknownHostException { InetAddress address_66_0 = InetAddress.getByName("172.24.66.0"); InetAddress address_66_255 = InetAddress.getByName("172.24.66.255"); InetAddress address_67_0 = InetAddress.getByName("172.24.67.0"); InetAddress address = address_66_0; for (int i = 0; i < 255; i++) { address = InetAddresses.increment(address); } assertEquals(address_66_255, address); address = InetAddresses.increment(address); assertEquals(address_67_0, address); InetAddress address_ffffff = InetAddress.getByName("255.255.255.255"); address = address_ffffff; try { address = InetAddresses.increment(address); fail(); } catch (IllegalArgumentException expected) { } }
private String findPublicHostname() { try { return InetAddress.getLocalHost().getHostName().toLowerCase(); } catch (UnknownHostException e) { // Java 7u5 and later on MacOS sometimes throws this unless the local hostname is in DNS // or hosts file. The exception message is the hostname followed by a colon and an error // message. final Matcher matcher = HOST_EXCEPTION_MESSAGE_PATTERN.matcher(e.getMessage()); if (matcher.matches()) { return matcher.group(1).toLowerCase(); } return InetAddresses.toUriString(internalIp); } }
public void testDecrementIPv6() throws UnknownHostException { InetAddress addressV6660 = InetAddress.getByName("2001:db8::6600"); InetAddress addressV666ff = InetAddress.getByName("2001:db8::66ff"); InetAddress addressV6670 = InetAddress.getByName("2001:db8::6700"); InetAddress address = addressV6670; address = InetAddresses.decrement(address); assertEquals(addressV666ff, address); for (int i = 0; i < 255; i++) { address = InetAddresses.decrement(address); } assertEquals(addressV6660, address); InetAddress addressV6000000 = InetAddress.getByName("0:0:0:0:0:0:0:0"); address = addressV6000000; try { address = InetAddresses.decrement(address); fail(); } catch (IllegalArgumentException expected) { } }
public void testDecrementIPv4() throws UnknownHostException { InetAddress address660 = InetAddress.getByName("172.24.66.0"); InetAddress address66255 = InetAddress.getByName("172.24.66.255"); InetAddress address670 = InetAddress.getByName("172.24.67.0"); InetAddress address = address670; address = InetAddresses.decrement(address); assertEquals(address66255, address); for (int i = 0; i < 255; i++) { address = InetAddresses.decrement(address); } assertEquals(address660, address); InetAddress address0000 = InetAddress.getByName("0.0.0.0"); address = address0000; try { address = InetAddresses.decrement(address); fail(); } catch (IllegalArgumentException expected) { } }
/** * Tests the SMTP settings from the initial setup form, rendering the result as JSON. * * @param setup the initial setup form. */ @Restrictions({ @Restrict({"SYSTEM_ADMIN", "SECURITY_ADMIN"}), @Restrict({"RESTRICTED_SYSTEM_ADMIN", "RESTRICTED_SECURITY_ADMIN"}) }) public static void testSmtpSettings(SetupForm setup) { setup.validateSmtp(); Validation.required("setup.smtpTo", setup.smtpTo); Validation.email("setup.smtpTo", setup.smtpTo); if (Validation.hasErrors()) { renderJSON(ValidationResponse.collectErrors()); } MailSettingsValidator.Settings settings = new MailSettingsValidator.Settings(); if (StringUtils.isNotEmpty(setup.nameservers) && !InetAddresses.isInetAddress(setup.smtpServer)) { Set<String> ips = Sets.newHashSet(setup.nameservers.split(",")); try { settings.server = DnsUtils.getHostIpAddress(ips, setup.smtpServer).getHostAddress(); } catch (ViPRException e) { renderJSON(ValidationResponse.invalid(e.getMessage())); } } else { settings.server = setup.smtpServer; } settings.port = ConfigProperties.getPort(setup.smtpPort, setup.smtpEnableTls); settings.username = setup.smtpUsername; settings.password = PasswordUtil.decryptedValue(setup.smtpPassword); settings.channel = StringUtils.equals("yes", setup.smtpEnableTls) ? "starttls" : "clear"; settings.authType = setup.smtpAuthType; settings.fromAddress = setup.smtpFrom; try { MailSettingsValidator.validate(settings, setup.smtpTo); } catch (RuntimeException e) { Logger.error(e, "Failed to send email"); Validation.addError(null, "setup.testEmail.failure", e.getMessage()); if (StringUtils.isEmpty(setup.nameservers)) { Validation.addError(null, "setup.smtpServer.invalidEmptyNameserver"); } } if (Validation.hasErrors()) { renderJSON(ValidationResponse.collectErrors()); } else { renderJSON(ValidationResponse.valid(MessagesUtils.get("setup.testEmail.success"))); } }
public class IpAddressConversion extends AbstractFunction<IpAddress> { public static final String NAME = "to_ip"; private static final InetAddress ANYV4 = InetAddresses.forString("0.0.0.0"); private final ParameterDescriptor<Object, Object> ipParam; private final ParameterDescriptor<String, String> defaultParam; public IpAddressConversion() { ipParam = ParameterDescriptor.object("ip").description("Value to convert").build(); defaultParam = ParameterDescriptor.string("default") .optional() .description("Used when 'ip' is null or malformed, defaults to '0.0.0.0'") .build(); } @Override public IpAddress evaluate(FunctionArgs args, EvaluationContext context) { final String ipString = String.valueOf(ipParam.required(args, context)); try { final InetAddress inetAddress = InetAddresses.forString(ipString); return new IpAddress(inetAddress); } catch (IllegalArgumentException e) { final Optional<String> defaultValue = defaultParam.optional(args, context); if (!defaultValue.isPresent()) { return new IpAddress(ANYV4); } try { return new IpAddress(InetAddresses.forString(defaultValue.get())); } catch (IllegalFormatException e1) { log.warn( "Parameter `default` for to_ip() is not a valid IP address: {}", defaultValue.get()); throw e1; } } } @Override public FunctionDescriptor<IpAddress> descriptor() { return FunctionDescriptor.<IpAddress>builder() .name(NAME) .returnType(IpAddress.class) .params(of(ipParam, defaultParam)) .description("Converts a value to an IPAddress using its string representation") .build(); } }
public class UniqueIscsiTargetBuilder implements Builder<UniqueIscsiTarget> { private static final Random random = new Random(); private String uuid = UUID.randomUUID().toString(); private String storageIpAddress = InetAddresses.fromInteger(random.nextInt()).getHostAddress(); private String storageAgentUrl = "http://" + randomAlphabetic(4) + ".example.com"; private IscsiTarget iscsiTarget = IscsiTargetBuilder.anIscsiTarget().build(); public static UniqueIscsiTargetBuilder aUniqueIscsiTarget() { return new UniqueIscsiTargetBuilder(); } @Override public UniqueIscsiTarget build() { return new UniqueIscsiTarget(uuid, storageIpAddress, storageAgentUrl, iscsiTarget); } }
@Override public Session toManagementSession() { SessionBuilder builder = new SessionBuilder(); builder.setSessionId(getSessionId()); IpAddress address; InetAddress address1 = InetAddresses.forString(header.getAddress()); if (address1 instanceof Inet4Address) { address = new IpAddress(new Ipv4Address(header.getAddress())); } else { address = new IpAddress(new Ipv6Address(header.getAddress())); } builder.setSourceHost(new Host(address)); Preconditions.checkState(DateAndTime.PATTERN_CONSTANTS.size() == 1); String formattedDateTime = dateFormatter.format(loginTime); Matcher matcher = dateTimePattern.matcher(formattedDateTime); Preconditions.checkState( matcher.matches(), "Formatted datetime %s does not match pattern %s", formattedDateTime, dateTimePattern); builder.setLoginTime(new DateAndTime(formattedDateTime)); builder.setInBadRpcs(new ZeroBasedCounter32(inRpcFail)); builder.setInRpcs(new ZeroBasedCounter32(inRpcSuccess)); builder.setOutRpcErrors(new ZeroBasedCounter32(outRpcError)); builder.setUsername(header.getUserName()); builder.setTransport(getTransportForString(header.getTransport())); builder.setOutNotifications(new ZeroBasedCounter32(outNotification)); builder.setKey(new SessionKey(getSessionId())); Session1Builder builder1 = new Session1Builder(); builder1.setSessionIdentifier(header.getSessionIdentifier()); builder.addAugmentation(Session1.class, builder1.build()); return builder.build(); }
public NodeInfo( String environment, String pool, String nodeId, InetAddress nodeIp, String location, String binarySpec, String configSpec) { Preconditions.checkNotNull(environment, "environment is null"); Preconditions.checkNotNull(pool, "pool is null"); Preconditions.checkArgument( environment.matches(NodeConfig.ENV_REGEXP), String.format("environment '%s' is invalid", environment)); Preconditions.checkArgument( pool.matches(NodeConfig.POOL_REGEXP), String.format("pool '%s' is invalid", pool)); this.environment = environment; this.pool = pool; if (nodeId != null) { this.nodeId = nodeId; } else { this.nodeId = UUID.randomUUID().toString(); } if (location != null) { this.location = location; } else { this.location = "/" + this.nodeId; } this.binarySpec = binarySpec; this.configSpec = configSpec; if (nodeIp != null) { this.publicIp = nodeIp; this.bindIp = nodeIp; } else { this.publicIp = findPublicIp(); this.bindIp = InetAddresses.fromInteger(0); } }
public static long ipToLong(String ip) throws ElasticsearchIllegalArgumentException { try { if (!InetAddresses.isInetAddress(ip)) { throw new ElasticsearchIllegalArgumentException( "failed to parse ip [" + ip + "], not a valid ip address"); } String[] octets = pattern.split(ip); if (octets.length != 4) { throw new ElasticsearchIllegalArgumentException( "failed to parse ip [" + ip + "], not a valid ipv4 address (4 dots)"); } return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) + (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]); } catch (Exception e) { if (e instanceof ElasticsearchIllegalArgumentException) { throw (ElasticsearchIllegalArgumentException) e; } throw new ElasticsearchIllegalArgumentException("failed to parse ip [" + ip + "]", e); } }