inet.ipaddr.IPAddress Java Examples

The following examples show how to use inet.ipaddr.IPAddress. 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: IPAddressProvider.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
/**
 * When a value provider produces no value, equality and comparison are based on the enum IPType,
 * which can by null.
 * @param o
 * @return
 */
default boolean providerEquals(IPAddressProvider other) throws IncompatibleAddressException {
	if(this == other) {
		return true;
	}
	IPAddress value = getProviderAddress();
	if(value != null) {
		IPAddress otherValue = other.getProviderAddress();
		if(otherValue != null) {
			return value.equals(otherValue);
		} else {
			return false;
		}
	}
	//this works with both null and also non-null since the type is an enum
	return getType() == other.getType();
}
 
Example #2
Source File: TestBase.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
boolean confirmHostStrings(IPAddress ipAddr, HostName ...strs) {
	for(HostName str : strs) {
		IPAddress a = str.getAddress();
		if(!ipAddr.equals(a)) {
			addFailure(new Failure("failed produced string: " + str, ipAddr));
			return false;
		}
		String again = str.toNormalizedString();
		str = new HostName(again);
		a = str.getAddress();
		if(!ipAddr.equals(a)) {
			addFailure(new Failure("failed produced string: " + str, ipAddr));
			return false;
		}
	}
	incrementTestCount();
	return true;
}
 
Example #3
Source File: HostTest.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
void testMasked(String masked, String mask, Integer prefixLength, String result) {
	HostName maskedHostStr = createHost(masked);
	IPAddress maskAddr = mask != null ? createAddress(mask).getAddress() : null;
	if(result != null) {
		IPAddress resultAddr = createAddress(result).getAddress();
		IPAddress maskedAddr = maskedHostStr.getAddress();
		if(!maskedAddr.equals(resultAddr)) {
			addFailure(new Failure("masked " + maskedAddr + " instead of expected " + resultAddr, maskedAddr));
		}
	}
	if(!Objects.equals(maskAddr, maskedHostStr.getMask())) {
		addFailure(new Failure("masked " + maskAddr + " instead of expected " + maskedHostStr.getMask(), maskedHostStr));
	}
	if(!Objects.equals(maskedHostStr.getNetworkPrefixLength(), prefixLength)) {
		addFailure(new Failure("masked prefix length was " + maskedHostStr.getNetworkPrefixLength() + " instead of expected " + prefixLength, maskedHostStr));
	}
	incrementTestCount();
}
 
Example #4
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
@Override
public int providerCompare(IPAddressProvider other) throws IncompatibleAddressException {
	if(this == other) {
		return 0;
	}
	if(adjustedVersion == null) {
		if(other.getType() == IPType.PREFIX_ONLY) {//both are PREFIX_ONLY
			return other.getProviderNetworkPrefixLength().intValue() - getProviderNetworkPrefixLength().intValue();
		}
		return IPType.PREFIX_ONLY.ordinal() - other.getType().ordinal();
	}
	IPAddress otherValue = other.getProviderAddress();
	if(otherValue != null) {
		return getProviderAddress().compareTo(otherValue);
	}
	return IPType.from(adjustedVersion).ordinal() - other.getType().ordinal();
}
 
Example #5
Source File: SpecialTypesTest.java    From IPAddress with 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 #6
Source File: TestBase.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
boolean confirmHostStrings(IPAddress ipAddr, boolean omitZone, String ...strs) {
	for(String str : strs) {
		HostName hostName = new HostName(str);
		IPAddress a = hostName.getAddress();
		if(omitZone) {
			IPv6Address ipv6Addr = ipAddr.toIPv6();
			ipAddr = new IPv6Address(ipv6Addr.getSection());
		}
		if(!ipAddr.equals(a)) {
			addFailure(new Failure("failed produced string: " + str, ipAddr));
			return false;
		}
		String again = hostName.toNormalizedString();
		hostName = new HostName(again);
		a = hostName.getAddress();
		if(!ipAddr.equals(a)) {
			addFailure(new Failure("failed produced string: " + str, ipAddr));
			return false;
		}
	}
	incrementTestCount();
	return true;
}
 
Example #7
Source File: TestBase.java    From IPAddress with 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 File: AddressDivisionBase.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
	int radix = getDefaultTextualRadix();
	IPStringOptions opts;
	switch(radix) {
	case 8:
		opts = OCTAL_PARAMS;
		break;
	case 16:
		opts = HEX_PARAMS;
		break;
	case 10:
		opts = DECIMAL_PARAMS;
		break;
	default:
		opts = new IPStringOptions.Builder(radix).setWildcards(new Wildcards(IPAddress.RANGE_SEPARATOR_STR)).toOptions();
		break;
	}
	StringBuilder builder = new StringBuilder(34);
	toParams(opts).appendSingleDivision(this, builder);
	return builder.toString();
}
 
Example #9
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPAddress getProviderAddress()  {
	if(adjustedVersion == null) {
		return null;
	}
	return super.getProviderAddress();
}
 
Example #10
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
CachedIPAddresses<IPAddress> createAddresses() {
	InetAddress loopback = InetAddress.getLoopbackAddress();
	boolean isIPv6 = loopback instanceof Inet6Address;
	IPAddress result;
	if(zone != null && zone.length() > 0 && isIPv6) {
		ParsedAddressCreator<? extends IPAddress, ?, ?, ?> addressCreator = options.getIPv6Parameters().getNetwork().getAddressCreator();
		result = addressCreator.createAddressInternal(loopback.getAddress(), zone);
	} else if(isIPv6) {
		result = options.getIPv6Parameters().getNetwork().getLoopback();
	} else {
		result = options.getIPv4Parameters().getNetwork().getLoopback();
	}
	return new CachedIPAddresses<IPAddress>(result);
}
 
Example #11
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPAddress getProviderHostAddress()  {
	if(adjustedVersion == null) {
		return null;
	}
	return super.getProviderHostAddress();
}
 
Example #12
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPAddressSeqRange getProviderSeqRange() {
	if(isProvidingAllAddresses()) {
		return null;
	}
	IPAddress mask = getProviderMask();
	if(mask != null && mask.getBlockMaskPrefixLength(true) == null) {
		// we must apply the mask
		IPAddress all = ParsedIPAddress.createAllAddress(adjustedVersion, ParsedHost.NO_QUALIFIER, null, options);
		IPAddress upper = all.getUpper().mask(mask);
		IPAddress lower = all.getLower();
		return lower.toSequentialRange(upper);
	}
	return super.getProviderSeqRange();
}
 
Example #13
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
CachedIPAddresses<?> createAddresses() {
	if(qualifier.equals(ParsedHost.NO_QUALIFIER)) {
		return new CachedIPAddresses<IPAddress>(ParsedIPAddress.createAllAddress(adjustedVersion, qualifier, originator, options));
	}
	return new CachedIPAddresses<IPAddress>(ParsedIPAddress.createAllAddress(adjustedVersion, qualifier, originator, options),
			ParsedIPAddress.createAllAddress(adjustedVersion, qualifier.getZone() != null ? new ParsedHostIdentifierStringQualifier(qualifier.getZone()) : ParsedHost.NO_QUALIFIER, originator, options));
}
 
Example #14
Source File: ParsedIPAddress.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
IPAddress getValForMask() {
	TranslatedResult<?,?> val = values;
	if(val == null || val.lowerSection == null) {
		synchronized(this) {
			val = values;
			if(val == null || val.lowerSection == null) {
				createAddresses(false, true, false);
				val = values;
				releaseSegmentData(); // As a mask value, we can release our data sooner, there will be no request for address or division grouping
			}
		}
	}
	return val.getValForMask();
}
 
Example #15
Source File: ParsedIPAddress.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPAddress getProviderHostAddress() throws IncompatibleAddressException {
	TranslatedResult<?,?> addrs = getCachedAddresses();
	if(addrs.mixedException != null) {
		throw addrs.mixedException;
	} else if(addrs.joinHostException != null) {
		throw addrs.joinHostException;
	}
	return addrs.getHostAddress();
}
 
Example #16
Source File: ParsedIPAddress.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPAddress getProviderAddress() throws IncompatibleAddressException {
	TranslatedResult<?,?> addrs = getCachedAddresses();
	if(addrs.mixedException != null) {
		throw addrs.mixedException;
	} else if(addrs.maskException != null) {
		throw addrs.maskException;
	} else if(addrs.joinAddressException != null) {
		throw addrs.joinAddressException;
	}
	return addrs.getAddress();
}
 
Example #17
Source File: IPv6Address.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPv6Address[] mergeToSequentialBlocks(IPAddress ...addresses) throws AddressConversionException {
	addresses = addresses.clone();
	for(int i = 0; i < addresses.length; i++) {
		addresses[i] = convertArg(addresses[i]);
	}
	List<IPAddressSegmentSeries> blocks = getMergedSequentialBlocks(this, addresses, getDefaultCreator());
	return blocks.toArray(new IPv6Address[blocks.size()]);
}
 
Example #18
Source File: ParsedHostIdentifierStringQualifier.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
IPAddress getMaskLower() {
	if(mergedMask != null) {
		return mergedMask;
	}
	if(mask != null) {
		return mask.getValForMask();
	}
	return null;
}
 
Example #19
Source File: TrieTest.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
void createSampleTree(IPv6AddressTrie tree, IPAddress addrs[]) {
	for(IPAddress addr : addrs) {
		if(addr.isIPv6()) {
			addr = Partition.checkBlockOrAddress(addr);
			if(addr != null) {
				IPv6Address address = addr.toIPv6();
				tree.add(address);
			}
		}
	}
}
 
Example #20
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPAddressDivisionSeries getDivisionGrouping() throws IncompatibleAddressException {
	if(isProvidingAllAddresses()) {
		return null;
	}
	IPAddressNetwork<?, ?, ?, ?, ?> network = adjustedVersion.isIPv4() ?
			options.getIPv4Parameters().getNetwork() : options.getIPv6Parameters().getNetwork();
	IPAddress mask = getProviderMask();
	if(mask != null && mask.getBlockMaskPrefixLength(true) == null) {
		// there is a mask
		Integer hostMaskPrefixLen = mask.getBlockMaskPrefixLength(false);
		if(hostMaskPrefixLen == null) { // not a host mask
			throw new IncompatibleAddressException(getProviderAddress(), mask, "ipaddress.error.maskMismatch");
		}
		IPAddress hostMask = network.getHostMask(hostMaskPrefixLen);
		return hostMask.toPrefixBlock();
	}
	IPAddressDivisionSeries grouping;
	if(adjustedVersion.isIPv4()) {
		grouping = new IPAddressDivisionGrouping(new IPAddressBitsDivision[] {
					new IPAddressBitsDivision(0, IPv4Address.MAX_VALUE, IPv4Address.BIT_COUNT, IPv4Address.DEFAULT_TEXTUAL_RADIX, network, qualifier.getEquivalentPrefixLength())
				}, network);
	} else if(adjustedVersion.isIPv6()) {
		byte upperBytes[] = new byte[16];
		Arrays.fill(upperBytes, (byte) 0xff);
		grouping = new IPAddressLargeDivisionGrouping(new IPAddressLargeDivision[] {new IPAddressLargeDivision(new byte[IPv6Address.BYTE_COUNT], upperBytes, IPv6Address.BIT_COUNT, IPv6Address.DEFAULT_TEXTUAL_RADIX, network, qualifier.getEquivalentPrefixLength())}, network);
	} else {
		grouping = null;
	}
	return grouping;
}
 
Example #21
Source File: TrieTest.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
void testAddressCheck() {
	IPAddress addr = createAddress("1.2.3.4/16").getAddress();
	PrefixConfiguration prefCon = addr.getNetwork().getPrefixConfiguration();
	if(!prefCon.allPrefixedAddressesAreSubnets()) {
		testConvertedBlock(addr, null);
	} else {
		testIPAddrBlock("1.2.3.4/16");
	}
	testIPAddrBlock("1.2.3.4");
	testIPAddrBlock("::");
	testNonBlock("1-3.2.3.4");
	testConvertedBlock("1.2.3.4-5", 31);
	testNonBlock("1.2.3.5-6");
	testConvertedBlock("1.2.3.4-7", 30);
	testNonBlock("::1-2:0");
	testNonBlock("::1-2:0/112");
	if(!prefCon.prefixedSubnetsAreExplicit()) {
		testConvertedBlock("::0-3:0/112", 110);
		testIPAddrBlock("::/64");
		testIPAddrBlock("1.2.0.0/16");
	} else {
		testNonBlock("::0-3:0/112");
		testConvertedBlock("::/64", null);
		testConvertedBlock("1.2.0.0/16", null);
	}
	MACAddress mac = createMACAddress("a:b:c:*:*:*").getAddress();
	mac = mac.setPrefixLength(48, false);
	testConvertedBlock(mac, 24);
	testMACAddrBlock("a:b:c:*:*:*");
	testNonMACBlock("a:b:c:*:2:*");
	testNonBlock("a:b:c:*:2:*"); // passes null into checkBlockOrAddress
	testMACAddrBlock("a:b:c:1:2:3");
}
 
Example #22
Source File: TrieTest.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
static <T extends IPAddress> void partitionForTrie(TestBase testBase, AddressTrie<T> trie, T subnet) {
	Partition.partitionWithSingleBlockSize(subnet).predicateForEach(trie::add);
	if(trie.size() != 15) {
		addFailure(testBase, "partition size unexpected " + trie.size() + ", expected " + 15, trie);
	}
	Map<T, TrieNode<T>> all = Partition.partitionWithSingleBlockSize(subnet).applyForEach(trie::getAddedNode);
	if(all.size() != 15) {
		addFailure(testBase, "map size unexpected " + trie.size() + ", expected " + 15, trie);
	}
	HashMap<T, TrieNode<T>> all2 = new HashMap<>();
	Partition.partitionWithSingleBlockSize(subnet).forEach(addr -> {
		TrieNode<T> node = trie.getAddedNode(addr);
		all2.put(addr, node);
	});
	if(!all.equals(all2)) {
		addFailure(testBase, "maps not equal " + all + " and " + all2, trie);
	}
	trie.clear();
	Partition.partitionWithSpanningBlocks(subnet).predicateForEach(trie::add);
	if(trie.size() != 4) {
		addFailure(testBase,"partition size unexpected " + trie.size() + ", expected " + 4, trie);
	}
	trie.clear();
	Partition.partitionWithSingleBlockSize(subnet).predicateForEach(trie::add);
	Partition.partitionWithSpanningBlocks(subnet).predicateForEach(trie::add);
	if(trie.size() != 18) {
		addFailure(testBase,"partition size unexpected " + trie.size() + ", expected " + 18, trie);
	}
	boolean allAreThere = Partition.partitionWithSingleBlockSize(subnet).predicateForEach(trie::contains);
	boolean allAreThere2 = Partition.partitionWithSpanningBlocks(subnet).predicateForEach(trie::contains);
	if(!(allAreThere && allAreThere2)) {
		addFailure(testBase,"partition contains check failing", trie);
	}
	testBase.incrementTestCount();
}
 
Example #23
Source File: SpecialTypesTest.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
void testEmptyLoopback() {
	HostName w = createHost("", HOST_OPTIONS); 
	if(w.isLoopback()) {
		addFailure(new Failure("failed: isSelf is " + w.isSelf(), w));
	}
	IPAddress addressEmptyValue = w.getAddress();
	if(!addressEmptyValue.isLoopback()) {
		addFailure(new Failure("failed: isSelf is " + addressEmptyValue.isLoopback(), w));
	}
	HostName w2 = createHost("", EMPTY_ADDRESS_OPTIONS);
	if(!w2.isLoopback()) {
		addFailure(new Failure("failed: isSelf is " + w2.isSelf(), w2));
	}
	incrementTestCount();
}
 
Example #24
Source File: TestRunner.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPAddress create(IPAddressKey addressKey) {
	if(addressKey.bytes.length == 4) {
		return new IPv4Address(addressKey.bytes);
	}
	return new IPv6Address(addressKey.bytes);
}
 
Example #25
Source File: IPv6Address.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
public IPv6Address[] spanWithSequentialBlocks(IPAddress other) throws AddressConversionException {
	return IPAddress.getSpanningSequentialBlocks(
			this,
			convertArg(other),
			IPv6Address::getLower,
			IPv6Address::getUpper,
			Address.ADDRESS_LOW_VALUE_COMPARATOR::compare,
			IPv6Address::withoutPrefixLength,
			getDefaultCreator());
}
 
Example #26
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
default int providerHashCode() throws IncompatibleAddressException {
	IPAddress value = getProviderAddress();
	if(value != null) {
		return value.hashCode();
	}
	return Objects.hashCode(getType());
}
 
Example #27
Source File: AddressTrie.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the previous address according to the trie ordering
 * 
 * @param <E>
 * @param addr
 * @return
 */
@SuppressWarnings("unchecked")
public static <E extends Address> E decrement(E addr) {
	if(addr.isZero()) {
		return null;
	}
	if(addr instanceof IPAddress) {
		IPAddress ipaddr = (IPAddress) addr;
		if(addr.isPrefixed()) {
			return (E) ipaddr.getLower().setPrefixLength(ipaddr.getPrefixLength() + 1).toMaxHost();
		}
		return (E) ipaddr.toPrefixBlock(ipaddr.getBitCount() - (ipaddr.getTrailingBitCount(true) + 1));
	}
	
	if(addr.isPrefixed()) {
		return (E) addr.getLower().setPrefixLength(addr.getPrefixLength() + 1).toPrefixBlock().getUpper();
	}
	int trailingBitCount = 0;
	for(int i = addr.getSegmentCount() - 1; i >= 0; i--) {
		AddressSegment seg = addr.getSegment(i);
		if(!seg.isZero()) {
			trailingBitCount += Integer.numberOfTrailingZeros(seg.getSegmentValue());
			break;
		}
		trailingBitCount += seg.getBitCount();
	}
	return (E) addr.setPrefixLength(addr.getBitCount() - (trailingBitCount + 1)).toPrefixBlock();
}
 
Example #28
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
default IPAddressSeqRange getProviderSeqRange() {
	IPAddress addr = getProviderAddress();
	if(addr != null) {
		return addr.toSequentialRange();
	}
	return null;
}
 
Example #29
Source File: IPAddressProvider.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
default boolean isSequential() {
	try {
		IPAddress addr = getProviderAddress();
		if(addr != null) {
			return addr.isSequential();
		}
	} catch(IncompatibleAddressException e) {}
	return false;
}
 
Example #30
Source File: ScoreCommand.java    From AntiVPN with 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;
}