Java Code Examples for inet.ipaddr.IPAddressString

The following examples show how to use inet.ipaddr.IPAddressString. These examples are extracted from open source projects. 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 Project: IPAddress   Source File: ParsedHost.java    License: Apache License 2.0 6 votes vote down vote up
public IPAddressString asGenericAddressString() {
	if(hasEmbeddedAddress()) {
		IPAddressProvider addressProvider = getAddressProvider();
		if(addressProvider.isProvidingAllAddresses()) {
			return new IPAddressString(IPAddress.SEGMENT_WILDCARD_STR, addressProvider.getParameters());
		} else if(addressProvider.isProvidingPrefixOnly()) {
			return new IPAddressString(IPAddressNetwork.getPrefixString(addressProvider.getProviderNetworkPrefixLength()), addressProvider.getParameters());
		} else if(addressProvider.isProvidingEmpty()) {
			return new IPAddressString("", addressProvider.getParameters());
		} else {
			try {
				IPAddress addr = addressProvider.getProviderAddress();
				return addr.toAddressString();
			} catch(IncompatibleAddressException e) {
				return new IPAddressString(originalStr, addressProvider.getParameters());
			}
		}
	}
	return null;
}
 
Example 2
Source Project: IPAddress   Source File: IPv6Address.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The base 85 string is described by RFC 1924
 * @return
 */
public String toBase85String() throws IncompatibleAddressException {
	//first we see if we obtained this address from a base 85 string
	//in the case of a prefix, applying the prefix changes the value
	IPAddressString originator = getAddressfromString();
	if(originator != null && (!isPrefixed() || getNetworkPrefixLength() == IPv6Address.BIT_COUNT) && originator.isBase85IPv6()) {
		return originator.toString();
	}
	String result;
	if(hasNoStringCache() || (result = stringCache.base85String) == null) {
		if(hasZone()) {
			stringCache.base85String = result = getSection().toBase85String(getZone());
		} else {
			result = getSection().toBase85String();//the cache is shared so no need to update it here
		}
	}
	return result;
}
 
Example 3
Source Project: IPAddress   Source File: TestRunner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
void runTest() {
	PrefixConfiguration ordering[] = new PrefixConfiguration[] {
		PrefixConfiguration.ALL_PREFIXED_ADDRESSES_ARE_SUBNETS,
		PrefixConfiguration.PREFIXED_ZERO_HOSTS_ARE_SUBNETS,
		PrefixConfiguration.EXPLICIT_SUBNETS,
	};
	int count = 0;
	while(count < ordering.length) {
		showMessage("");
		PrefixConfiguration prefConf = ordering[count++];
		TestBase.prefixConfiguration = prefConf;
		IPv4AddressNetwork.setDefaultPrefixConfiguration(prefConf);
		IPv6AddressNetwork.setDefaultPrefixConfiguration(prefConf);
		MACAddressNetwork.setDefaultPrefixConfiguration(prefConf);
		showMessage("testing with " + prefConf);
		showMessage("count of 1.2.0.0/16 is " + new IPAddressString("1.2.0.0/16").getAddress().getCount());
		showMessage("count of 1.2.3.4/16 is " + new IPAddressString("1.2.3.4/16").getAddress().getCount());
		runBattery();
		Address.defaultIpv4Network().clearCaches();
		Address.defaultIpv6Network().clearCaches();
		Address.defaultMACNetwork().clearCaches();
	}
}
 
Example 4
Source Project: IPAddress   Source File: MACAddressTest.java    License: Apache License 2.0 6 votes vote down vote up
void testDelimitedCount(String str, int expectedCount) {
	Iterator<String> strings = MACAddressString.parseDelimitedSegments(str);
	HashSet<MACAddress> set = new HashSet<MACAddress>();
	int count = 0;
	try {
		while(strings.hasNext()) {
			set.add(createMACAddress(strings.next()).toAddress());
			count++;
		}
		if(count != expectedCount || set.size() != count || count != MACAddressString.countDelimitedAddresses(str)) {
			addFailure(new Failure("count mismatch, count: " + count + " set count: " + set.size() + " calculated count: " + IPAddressString.countDelimitedAddresses(str) + " expected: " + expectedCount));
		}
	} catch (AddressStringException | IncompatibleAddressException e) {
		addFailure(new Failure("threw unexpectedly " + str));
	}
	incrementTestCount();
}
 
Example 5
Source Project: IPAddress   Source File: TestBase.java    License: Apache License 2.0 6 votes vote down vote up
void testIPv6Strings(IPAddressString w, IPAddress ipAddr,  
		String normalizedString,
		String normalizedWildcardString,
		String canonicalWildcardString,
		String sqlString, 
		String fullString,
		String compressedString,
		String canonicalString,
		String subnetString,
		String compressedWildcardString,
		String mixedStringNoCompressMixed,
		String mixedStringNoCompressHost,
		String mixedStringCompressCoveredHost,
		String mixedString,
		String reverseDNSString,
		String uncHostString,
		String base85String,
		String singleHex,
		String singleOctal) {
	
	testStrings(w, ipAddr, normalizedString, normalizedWildcardString, canonicalWildcardString, sqlString, fullString, compressedString, canonicalString, subnetString, subnetString, compressedWildcardString, reverseDNSString, uncHostString, singleHex, singleOctal);
	
	//now test some IPv6-only strings
	testIPv6OnlyStrings(w, ipAddr.toIPv6(), mixedStringNoCompressMixed,
			mixedStringNoCompressHost, mixedStringCompressCoveredHost, mixedString, base85String);
}
 
Example 6
Source Project: IPAddress   Source File: TestBase.java    License: Apache License 2.0 6 votes vote down vote up
boolean confirmAddrStrings(IPAddress ipAddr, String ...strs) {
	for(String str : strs) {
		if(str == null) {
			continue;
		}
		IPAddressString addrString = createAddress(str, DEFAULT_BASIC_VALIDATION_OPTIONS);
		IPAddress addr = addrString.getAddress();
		if(!ipAddr.equals(addr)) {
			addFailure(new Failure("failed produced string: " + str, ipAddr));
			addrString = createAddress(str, DEFAULT_BASIC_VALIDATION_OPTIONS);
			addrString.getAddress();
			return false;
		}
	}
	incrementTestCount();
	return true;
}
 
Example 7
Source Project: IPAddress   Source File: TestBase.java    License: Apache License 2.0 6 votes vote down vote up
void testHostAddress(String addressStr) {
	IPAddressString str = createAddress(addressStr);
	IPAddress address = str.getAddress();
	if(address != null) {
		IPAddress hostAddress = str.getHostAddress();
		int prefixIndex = addressStr.indexOf(IPAddress.PREFIX_LEN_SEPARATOR);
		if(prefixIndex < 0) {
			if(!address.equals(hostAddress) || !address.contains(hostAddress)) {
				addFailure(new Failure("failed host address with no prefix: " + hostAddress + " expected: " + address, str));
			}
		} else {
			String substr = addressStr.substring(0, prefixIndex);
			IPAddressString str2 = createAddress(substr);
			IPAddress address2 = str2.getAddress();
			if(!address2.equals(hostAddress)) {
				addFailure(new Failure("failed host address: " + hostAddress + " expected: " + address2, str));
			}
		}
	}
}
 
Example 8
Source Project: IPAddress   Source File: SpecialTypesTest.java    License: Apache License 2.0 6 votes vote down vote up
void testAllValues(IPVersion version, BigInteger count) {
	HostName hostAll = createHost("*", HOST_OPTIONS);
	IPAddressString addressAllStr = createAddress("*", ADDRESS_OPTIONS);
	IPAddress addressAll = addressAllStr.getAddress(version);
	String address2Str = version.isIPv4() ? "*.*.*.*" : "*:*:*:*:*:*:*:*";
	IPAddress address = createAddress(address2Str, ADDRESS_OPTIONS).getAddress();
	if(!addressAll.equals(address)) {
		addFailure(new Failure("no match " + address, addressAll));
	} else if(addressAll.compareTo(address) != 0) {
		addFailure(new Failure("no match " + address, addressAll));
	} else if(!addressAll.getCount().equals(count)) {
		addFailure(new Failure("no count match ", addressAll));
	} else {
		addressAll = hostAll.asAddress(version);
		if(!addressAll.equals(address)) {
			addFailure(new Failure("no match " + address, addressAll));
		} else if(addressAll.compareTo(address) != 0) {
			addFailure(new Failure("no match " + address, addressAll));
		} else if(!addressAll.getCount().equals(count)) {
			addFailure(new Failure("no count match ", addressAll));
		}
	}
	incrementTestCount();
}
 
Example 9
Source Project: AntiVPN   Source File: ScoreCommand.java    License: MIT License 5 votes vote down vote up
private Set<String> getIPs(String mask, int count) {
    Set<String> retVal = new HashSet<>();
    IPAddress range = new IPAddressString(mask).getAddress();

    int fails = 0;
    while (retVal.size() < count && fails < 1000) {
        long getIndex = fairRoundedRandom(0L, range.getCount().longValue());
        long i = 0;
        for (IPAddress ip : range.getIterable()) {
            if (i == getIndex) {
                String str = ip.toCanonicalString();
                int idx = str.indexOf('/');
                if (idx > -1) {
                    str = str.substring(0, idx);
                }
                if (!retVal.add(str)) {
                    fails++;
                }
                if (retVal.size() >= count || fails >= 1000) {
                    break;
                }
                getIndex = fairRoundedRandom(0L, range.getCount().longValue());
                if (getIndex <= i) {
                    break;
                }
            }
            i++;
        }
    }

    return retVal;
}
 
Example 10
Source Project: AntiVPN   Source File: ValidationUtil.java    License: MIT License 5 votes vote down vote up
public static boolean isValidIPRange(String range) {
    if (range == null || range.isEmpty()) {
        return false;
    }
    try {
        return new IPAddressString(range).toAddress().isMultiple();
    } catch (AddressStringException ignored) { return false; }
}
 
Example 11
Source Project: AntiVPN   Source File: ValidationUtil.java    License: MIT License 5 votes vote down vote up
public static boolean isValidIp(String ip) {
    if (ip == null || ip.isEmpty()) {
        return false;
    }
    try {
        return !new IPAddressString(ip).toAddress().isMultiple();
    } catch (AddressStringException ignored) { return false; }
}
 
Example 12
Source Project: AntiVPN   Source File: ScoreCommand.java    License: MIT License 5 votes vote down vote up
private Set<String> getIPs(String mask, int count) {
    Set<String> retVal = new HashSet<>();
    IPAddress range = new IPAddressString(mask).getAddress();

    int fails = 0;
    while (retVal.size() < count && fails < 1000) {
        long getIndex = fairRoundedRandom(0L, range.getCount().longValue());
        long i = 0;
        for (IPAddress ip : range.getIterable()) {
            if (i == getIndex) {
                String str = ip.toCanonicalString();
                int idx = str.indexOf('/');
                if (idx > -1) {
                    str = str.substring(0, idx);
                }
                if (!retVal.add(str)) {
                    fails++;
                }
                if (retVal.size() >= count || fails >= 1000) {
                    break;
                }
                getIndex = fairRoundedRandom(0L, range.getCount().longValue());
                if (getIndex <= i) {
                    break;
                }
            }
            i++;
        }
    }

    return retVal;
}
 
Example 13
Source Project: AntiVPN   Source File: ScoreCommand.java    License: MIT License 5 votes vote down vote up
private Set<String> getIPs(String mask, int count) {
    Set<String> retVal = new HashSet<>();
    IPAddress range = new IPAddressString(mask).getAddress();

    int fails = 0;
    while (retVal.size() < count && fails < 1000) {
        long getIndex = fairRoundedRandom(0L, range.getCount().longValue());
        long i = 0;
        for (IPAddress ip : range.getIterable()) {
            if (i == getIndex) {
                String str = ip.toCanonicalString();
                int idx = str.indexOf('/');
                if (idx > -1) {
                    str = str.substring(0, idx);
                }
                if (!retVal.add(str)) {
                    fails++;
                }
                if (retVal.size() >= count || fails >= 1000) {
                    break;
                }
                getIndex = fairRoundedRandom(0L, range.getCount().longValue());
                if (getIndex <= i) {
                    break;
                }
            }
            i++;
        }
    }

    return retVal;
}
 
Example 14
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IPAddressProvider validateAddress(IPAddressString fromString) throws AddressStringException {
	String str = fromString.toString();
	IPAddressStringParameters validationOptions = fromString.getValidationOptions();
	ParsedIPAddress pa = new ParsedIPAddress(fromString, str, validationOptions);
	validateIPAddress(validationOptions, str, 0, str.length(), pa, false);
	return chooseProvider(fromString, str, validationOptions, pa,
		parseAddressQualifier(str, validationOptions, null, pa, str.length()));
}
 
Example 15
Source Project: IPAddress   Source File: IPAddressAllTest.java    License: Apache License 2.0 5 votes vote down vote up
void testAllContains(String cidr1, String cidr2, boolean result, boolean equal) {
	IPAddressString wstr = createAddress(cidr1);
	IPAddressString w2str = createAddress(cidr2);
	
	testStringContains(result, equal, wstr, w2str);

	incrementTestCount();
}
 
Example 16
Source Project: IPAddress   Source File: TestRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IPAddressString create(IPAddressStringKey addressStringKey) {
	if(addressStringKey.options == null) {
		return new IPAddressString(addressStringKey.keyString, TestBase.ADDRESS_OPTIONS);
	}
	return new IPAddressString(addressStringKey.keyString, addressStringKey.options);
}
 
Example 17
Source Project: IPAddress   Source File: TestRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IPAddressString createAddress(IPAddressStringKey key) {
	if(CACHING) {
		return cache.getFromAddressStringMap(key, ipAddressStringCreator);
	}
	return ipAddressStringCreator.create(key);
}
 
Example 18
Source Project: IPAddress   Source File: MACAddressRangeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected IPAddressString createAddress(String x) {
	if(x.indexOf(IPAddress.RANGE_SEPARATOR) != -1) {
		return createAddress(x, IPAddressRangeTest.WILDCARD_AND_RANGE_ADDRESS_OPTIONS);
	}
	return createAddress(x, IPAddressRangeTest.WILDCARD_ONLY_ADDRESS_OPTIONS);
}
 
Example 19
Source Project: IPAddress   Source File: TestBase.java    License: Apache License 2.0 5 votes vote down vote up
boolean confirmAddrStrings(IPAddress ipAddr, IPAddressString ...strs) {
	for(IPAddressString str : strs) {
		IPAddress addr = str.getAddress();
		if(!ipAddr.equals(addr)) {
			addFailure(new Failure("failed produced string: " + str, ipAddr));
			return false;
		}
	}
	incrementTestCount();
	return true;
}
 
Example 20
Source Project: IPAddress   Source File: TrieTest.java    License: Apache License 2.0 5 votes vote down vote up
void createSampleTree(IPv6AddressTrie tree, String addrs[]) {
	for(String addr : addrs) {
		IPAddressString addressStr = createAddress(addr);
		if(addressStr.isIPv6()) {
			IPv6Address address = addressStr.getAddress().toIPv6();
			tree.add(address);
		}
	}
}
 
Example 21
Source Project: IPAddress   Source File: TrieTest.java    License: Apache License 2.0 5 votes vote down vote up
void createSampleTree(IPv4AddressTrie tree, String addrs[]) {
	for(String addr : addrs) {
		IPAddressString addressStr = createAddress(addr);
		if(addressStr.isIPv4()) {
			IPv4Address address = addressStr.getAddress().toIPv4();
			tree.add(address);
		}
	}
}
 
Example 22
Source Project: IPAddress   Source File: SpecialTypesTest.java    License: Apache License 2.0 5 votes vote down vote up
void testIPv4Strings(String addr, boolean explicit, String normalizedString, String normalizedWildcardString, String sqlString, String fullString, String reverseDNSString, String singleHex, String singleOctal) {
	IPAddressString w = createAddress(addr, ADDRESS_OPTIONS);
	IPAddress ipAddr;
	if(explicit) {
		ipAddr = w.getAddress(IPVersion.IPV4);
	} else {
		ipAddr = w.getAddress();
	}
	testStrings(w, ipAddr, normalizedString, normalizedWildcardString, normalizedWildcardString, sqlString, fullString, 
			normalizedString, normalizedString, normalizedWildcardString, normalizedString, normalizedWildcardString, reverseDNSString, normalizedString,
			singleHex, singleOctal);
}
 
Example 23
Source Project: IPAddress   Source File: SpecialTypesTest.java    License: Apache License 2.0 5 votes vote down vote up
void testAllValues() {
	HostName hostAll = createHost("*", HOST_OPTIONS);
	IPAddressString addressAll = createAddress("*", ADDRESS_OPTIONS);
	MACAddressString macAll = createMACAddress("*", MAC_OPTIONS);
	if(addressAll.getAddress() != null) {
		addFailure(new Failure("non null", addressAll));
	} else if(hostAll.asAddress() != null) {
		addFailure(new Failure("non null", hostAll));
	} else if(hostAll.getAddress() != null) {
		addFailure(new Failure("non null", hostAll));
	} else if(macAll.getAddress() == null) {
		addFailure(new Failure("null", macAll));
	}
	incrementTestCount();
}
 
Example 24
Source Project: IPAddress   Source File: SpecialTypesTest.java    License: Apache License 2.0 5 votes vote down vote up
void testLoopback(String host, boolean isSelf) {
	HostName w = createHost(host, HOST_OPTIONS);
	if(isSelf != w.isLoopback()) {
		addFailure(new Failure("failed: isSelf is " + isSelf, w));
	}
	IPAddressString w2 = createAddress(host, ADDRESS_OPTIONS);
	if(isSelf != w2.isLoopback()) {
		addFailure(new Failure("failed: isSelf is " + isSelf, w));
	}
	incrementTestCount();
}
 
Example 25
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static IPAddressProvider chooseProvider(
		final HostIdentifierString originator,
		final CharSequence fullAddr,
		final IPAddressStringParameters validationOptions,
		final ParsedIPAddress parseData,
		final ParsedHostIdentifierStringQualifier qualifier) throws AddressStringException {
	IPVersion version = parseData.getProviderIPVersion();
	if(version == null) {
		version = qualifier.inferVersion(validationOptions);
		IPVersion optionsVersion = validationOptions.inferVersion();
		if(version == null) {
			parseData.setVersion(version = optionsVersion);
		} else if(optionsVersion != null && !version.equals(optionsVersion)) {
			throw new AddressStringException(fullAddr, version == IPVersion.IPV6 ? "ipaddress.error.ipv6" : "ipaddress.error.ipv4");
		}
		AddressParseData addressParseData = parseData.getAddressParseData();
		if(addressParseData.isProvidingEmpty()) {
			Integer networkPrefixLength = qualifier.getNetworkPrefixLength();
			if(networkPrefixLength != null) {
				int prefLen = networkPrefixLength;
				if(validationOptions == IPAddressString.DEFAULT_VALIDATION_OPTIONS && networkPrefixLength <= IPv6Address.BIT_COUNT) {
					int index = version == null ? 0 : version.isIPv4() ? 1 : 2;
					MaskCreator cached[] = MASK_CACHE[index];
					if(cached == null) {
						MASK_CACHE[index] = cached = new MaskCreator[IPv6Address.BIT_COUNT + 1];
					}
					MaskCreator result = cached[prefLen];
					if(result == null) {
						cached[prefLen] = result = new MaskCreator(networkPrefixLength, version, IPAddressString.DEFAULT_VALIDATION_OPTIONS);
					}
					return result;
				}
				return new MaskCreator(networkPrefixLength, version, validationOptions);
			} else {
				//Note: we do not support loopback with zone, it seems the loopback is never associated with a link-local zone
				if(validationOptions.emptyIsLoopback) {
					if(validationOptions == IPAddressString.DEFAULT_VALIDATION_OPTIONS) {
						return LOOPBACK_CACHE;
					}
					return new LoopbackCreator(validationOptions);
				}
				return IPAddressProvider.EMPTY_PROVIDER;
			}
		} else { //isAll
			//We also need the AllCreator to use the equivalent prefix length, much like in ParsedIPAddress
			return new AllCreator(qualifier, version, originator, validationOptions);
		}
	} else {
		if(parseData.isZoned() && version.isIPv4()) {
			throw new AddressStringException(fullAddr, "ipaddress.error.only.ipv6.has.zone");
		}
		parseData.setQualifier(qualifier);
		checkSegments(fullAddr, validationOptions, parseData);
		return parseData;
	}
}
 
Example 26
Source Project: IPAddress   Source File: IPAddressAllTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected IPAddressString createInetAtonAddress(String x) {
	return createAddress(x);
}
 
Example 27
Source Project: IPAddress   Source File: IPAddressAllTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected IPAddressString createAddress(String x) {
	return createAddress(x, DEFAULT_OPTIONS);
}
 
Example 28
Source Project: IPAddress   Source File: IPAddressAllTest.java    License: Apache License 2.0 4 votes vote down vote up
void testCaches(Map<String, IPAddressString> map, boolean testSize, boolean useBytes) {
	IPAddressStringGenerator cache = new IPAddressStringGenerator(map);
	testCache(ADDRESS_SAMPLING, cache, str -> createAddress(str), testSize, useBytes);
}
 
Example 29
Source Project: IPAddress   Source File: HostRangeTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected IPAddressString createAddress(String x) {
	IPAddressStringKey key = new IPAddressStringKey(x, ADDRESS_WILDCARD_OPTIONS);
	return createAddress(key);
}
 
Example 30
Source Project: IPAddress   Source File: HostAllTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected IPAddressString createAddress(String x) {
	IPAddressStringKey key = new IPAddressStringKey(x, DEFAULT_OPTIONS);
	return createAddress(key);
}