public class IPAddressString extends Object implements HostIdentifierString, Comparable<IPAddressString>
This supports a much wider range of address string formats than InetAddress.getByName. It supports subnet formats, provides specific error messages, and allows more specific configuration.
You can control all of the supported formats using IPAddressStringParameters.Builder
to build a parameters instance of IPAddressStringParameters
.
When not using the constructor that takes a IPAddressStringParameters
, a default instance of IPAddressStringParameters
is used that is generally permissive.
Subnets are supported:
You can combine these variations, such as 1.*.2-3.4/255.255.255.0
IPv6 is fully supported:
All of the above subnet variations work for IPv6, whether network prefix lengths, masks, ranges or wildcards. Similarly, all the above subnet variations work for any supported IPv4 format, such as the standard dotted-decimal IPv4 format as well as the inet_aton formats listed below.
This class support all address formats of the C routine inet_pton and the Java method java.net.InetAddress.getByName. This class supports all IPv4 address formats of the C routine inet_aton as follows:
Note that there is ambiguity when supporting both inet_aton octal and dotted-decimal leading zeros, like 010.010.010.010 which can be interpreted as octal or decimal, thus it can be either 8.8.8.8 or 10.10.10.10, with the default behaviour using the former interpretation
This behaviour can be controlled by IPAddressStringParameters.Builder.getIPv4AddressParametersBuilder()
and
IPv4AddressStringParameters.Builder.allowLeadingZeros(boolean)
Some additional formats:
#getAddress(IPVersion)
or #toAddress(IPVersion)
If you have an address in which segments have been delimited with commas, such as "1,2.3.4,5.6", you can parse this with parseDelimitedSegments(String)
which gives an iterator of strings. For "1,2.3.4,5.6" you will iterate through "1.3.4.6", "1.3.5.6", "2.3.4.6" and "2.3.5.6".
You can count the number of elements in such an iterator with countDelimitedAddresses(String)
.
Each string can then be used to construct an IPAddressString.
IPAddress
address = new IPAddressString
("1.2.3.4").getAddress()
;
If your application takes user input IP addresses, you can validate with:
try {
IPAddress
address = new IPAddressString("1.2.3.4").toAddress()
;
} catch(AddressStringException
e) {
//e.getMessage() provides description of validation failure
}
Most address strings can be converted to an IPAddress object using getAddress()
or toAddress()
. In most cases the IP version is determined by the string itself.
There are a few exceptions, cases in which the version is unknown or ambiguous, for which getAddress()
returns null:
#getAddress(IPVersion)
to get an address.#getAddress(IPVersion)
to get an address representing either all IPv4 or all IPv6 addresses.#getAddress(IPVersion)
to get the loopback version of your choice.
The other exception is a subnet in which the range of values in a segment of the subnet are not sequential, for which getAddress()
throws IncompatibleAddressException
because there is no single IPAddress value, there would be many.
An IPAddress instance requires that all segments can be represented as a range of values.
There are only two unusual circumstances when this can occur:
This class is thread-safe. In fact, IPAddressString objects are immutable. An IPAddressString object represents a single IP address representation that cannot be changed after construction. Some of the derived state is created upon demand and cached, such as the derived IPAddress instances.
This class has a few methods with analogs in IPAddress, such as contains(IPAddressString)
, getSequentialRange()
,
prefixEquals(IPAddressString)
, isIPv4()
, and isIPv6()
.
Such methods are provided to make creating the IPAddress instance unnecessary when no such IPAddress instance is needed for other reasons.
For some methods, like getSequentialRange()
and getDivisionGrouping()
,
there might not even be an associated IPAddress due to IncompatibleAddressException.
However, this is generally only the case with subnets that have non-standard and unusual formats or masks.
Modifier and Type | Field and Description |
---|---|
static IPAddressStringParameters |
DEFAULT_VALIDATION_OPTIONS |
SEGMENT_VALUE_DELIMITER
Constructor and Description |
---|
IPAddressString(String addr)
Constructs an IPAddressString instance using the given String instance.
|
IPAddressString(String addr,
IPAddressStringParameters valOptions) |
Modifier and Type | Method and Description |
---|---|
IPAddressString |
adjustPrefixBySegment(boolean nextSegment)
Increases or decreases prefix length to the next segment boundary of the given address version's standard segment boundaries.
|
IPAddressString |
adjustPrefixLength(int adjustment)
Increases or decreases prefix length by the given increment.
|
int |
compareTo(IPAddressString other)
All address strings are comparable.
|
boolean |
contains(IPAddressString other)
Returns whether the address subnet identified by this address string contains the address identified by the given string.
|
String |
convertToPrefixLength()
Converts this address to a prefix length
|
static int |
countDelimitedAddresses(String str)
Given a string with comma delimiters to denote segment elements, this method will count the possible combinations.
|
boolean |
equals(Object o)
Two IPAddressString objects are equal if they represent the same set of addresses.
|
IPAddress |
getAddress()
If this represents an ip address, returns that address.
|
IPAddress |
getAddress(IPAddress.IPVersion version)
Similar to
toAddress(inet.ipaddr.IPAddress.IPVersion) , but returns null rather than throwing an exception with the address is invalid or does not match the supplied version. |
AddressStringException |
getAddressStringException()
Returns the parse exception thrown by validate, rather than throwing it.
|
IPAddressDivisionSeries |
getDivisionGrouping()
Returns a representation of the address string, the address string represented "as-is", converted to value ranges with bit sizes matching the original string.
|
IPAddress |
getHostAddress()
If this address string was constructed from a host address with prefix length,
then this provides just the host address, rather than the address
provided by
getAddress() that incorporates the prefix. |
IPAddress.IPVersion |
getIPVersion()
Returns the IP address version if
isIPAddress() returns true, otherwise returns null |
IPAddress |
getMask()
If a mask was provided with this address string, this returns the resulting mask value.
|
Integer |
getNetworkPrefixLength()
If this address is a valid address with an associated network prefix length then this returns that prefix length, otherwise returns null.
|
IPAddressSeqRange |
getSequentialRange()
Returns the range of sequential addresses from the lowest address specified in this address string to the highest.
|
IPAddressStringParameters |
getValidationOptions() |
int |
hashCode() |
boolean |
isAllAddresses()
Returns true if the string represents all IP addresses, such as the string "*"
You can denote all IPv4 addresses with *.*, or all IPv6 addresses with *:*
|
boolean |
isBase85IPv6()
If this address string represents an IPv6 address, returns whether the string was base 85
|
boolean |
isEmpty()
Returns true if the address string is empty (zero-length).
|
boolean |
isIPAddress()
Returns whether the address represents a valid specific IP address or subnet, either IPv4 or IPv6,
as opposed to an empty string, the address representing all addresses of all types, a prefix length, or an invalid format.
|
boolean |
isIPv4()
Returns true if the address is IPv4 (with or without a network prefix, with or without wildcard segments).
|
boolean |
isIPv4Mapped()
Returns true if the address is an IPv6 IPv4-mapped address.
|
boolean |
isIPv6()
Returns true if the address is IPv6 (with or without a network prefix, with or without wildcard segments).
|
boolean |
isLoopback()
Returns whether this string represents a loopback IP address.
|
boolean |
isMixedIPv6()
If this address string represents an IPv6 address, returns whether the lower 4 bytes were represented as IPv4
|
boolean |
isPrefixed()
Returns whether this address string has an associated prefix length.
|
boolean |
isPrefixOnly()
Returns whether this address string represents only a prefix length with no associated address value,
as opposed to an empty string, an address with or without a prefix length, or an invalid format.
|
boolean |
isSequential()
Returns whether the addresses returned by this IPAddressString are sequential,
meaning that if any address has a numerical value that lies in between the numerical values of two addresses represented by this IPAddressString,
then that address is also represented by this IPAddressString.
|
boolean |
isValid()
Returns whether this is a valid address string format.
|
boolean |
isZero()
Returns whether this string represents an IP address whose value is zero.
|
static Iterator<String> |
parseDelimitedSegments(String str)
Given a string with comma delimiters to denote segment elements, this method will provide an iterator to iterate through the possible combinations.
|
boolean |
prefixContains(IPAddressString other)
Similar to
prefixEquals(IPAddressString) , but instead returns whether the prefix of this address contains the same of the given address,
using the prefix length of this address. |
boolean |
prefixEquals(IPAddressString other)
Similar to
equals(Object) , but instead returns whether the prefix of this address matches the same of the given address,
using the prefix length of this address. |
IPAddress |
toAddress()
Produces the
IPAddress corresponding to this IPAddressString. |
IPAddress |
toAddress(IPAddress.IPVersion version)
Produces the
IPAddress of the specified address version corresponding to this IPAddressString. |
IPAddressDivisionSeries |
toDivisionGrouping()
Returns a representation of the address string, the address string represented "as-is", converted to value ranges with bit sizes matching the original string.
|
IPAddress |
toHostAddress()
If this address string was constructed from a string comprising of a host address with prefix length or mask,
then this provides just the host address, rather than the address with the prefix or mask applied that is
provided by
toAddress() . |
String |
toNormalizedString()
provides a normalized String representation for the host identified by this HostIdentifierString instance
|
IPAddressSeqRange |
toSequentialRange()
Returns the range of sequential addresses from the lowest address specified in this address string to the highest.
|
String |
toString()
Gives us the original string provided to the constructor.
|
void |
validate()
Validates that this string is a valid address, and if not, throws an exception with a descriptive message indicating why it is not.
|
void |
validateIPv4()
Validates that this string is a valid IPv4 address, and if not, throws an exception with a descriptive message indicating why it is not.
|
void |
validateIPv6()
Validates that this string is a valid IPv6 address, and if not, throws an exception with a descriptive message indicating why it is not.
|
static void |
validateNetworkPrefix(IPAddress.IPVersion ipVersion,
int networkPrefixLength,
boolean allowPrefixesBeyondAddressSize) |
static int |
validateNetworkPrefixLength(IPAddress.IPVersion ipVersion,
CharSequence networkPrefixLength)
Validates that the string has the format "/x" for a valid prefix length x.
|
public static final IPAddressStringParameters DEFAULT_VALIDATION_OPTIONS
public IPAddressString(String addr)
addr
- the address in string format, either IPv4 like a.b.c.d or IPv6 like a:b:c:d:e:f:g:h or a:b:c:d:e:f:h.i.j.k or a::b or some other valid IPv4 or IPv6 form.
IPv6 addresses are allowed to terminate with a scope id which starts with a % symbol.
Both types of addresses can terminate with a network prefix value like a.b.c.d/24 or ::/24
Optionally, you can specify just a network prefix value like /24, which represents the associated masks 255.255.255.0/24 or ffff:ff00::/24.
Both IPv4 and IPv6 addresses can terminate with a mask instead of a prefix length, like a.b.c.d/255.0.0.0 or ::/ffff:: If a terminating mask is equivalent to a network prefix, then it will be the same as specifying the prefix, so a.b.c.d/16 is the same as a.b.c.d/255.255.0.0 If a terminating mask is not equivalent to a network prefix, then the mask will simply be applied to the address to produce a single address.
You can also alter the addresses to include ranges using the wildcards * and -, such as 1.*.1-2.3.
public IPAddressString(String addr, IPAddressStringParameters valOptions)
addr
- the address in string format
This constructor allows you to alter the default validation options.public IPAddressStringParameters getValidationOptions()
public boolean isPrefixed()
getNetworkPrefixLength()
public Integer getNetworkPrefixLength()
public IPAddress getMask()
public boolean isIPAddress()
public boolean isAllAddresses()
public boolean isPrefixOnly()
public boolean isEmpty()
public boolean isIPv4()
public boolean isIPv6()
public boolean isIPv4Mapped()
public boolean isMixedIPv6()
public boolean isBase85IPv6()
public IPAddress.IPVersion getIPVersion()
isIPAddress()
returns true, otherwise returns nullpublic boolean isLoopback()
InetAddress.isLoopbackAddress()
public boolean isZero()
public boolean isValid()
public AddressStringException getAddressStringException()
See validate()
or isValid()
public void validateIPv4() throws AddressStringException
AddressStringException
public void validateIPv6() throws AddressStringException
AddressStringException
public void validate() throws AddressStringException
validate
in interface HostIdentifierString
AddressStringException
public static int validateNetworkPrefixLength(IPAddress.IPVersion ipVersion, CharSequence networkPrefixLength) throws PrefixLenException
ipVersion
- IPv4, IPv6, or null if you do not know in which case it will be assumed that it can be eithernetworkPrefixLength
- the network prefix length integer as a string, eg "24"IncompatibleAddressException
- if invalid with an appropriate messagePrefixLenException
public static void validateNetworkPrefix(IPAddress.IPVersion ipVersion, int networkPrefixLength, boolean allowPrefixesBeyondAddressSize) throws PrefixLenException
PrefixLenException
public int compareTo(IPAddressString other)
compareTo
in interface Comparable<IPAddressString>
other
- public boolean prefixEquals(IPAddressString other)
equals(Object)
, but instead returns whether the prefix of this address matches the same of the given address,
using the prefix length of this address.
In other words, determines if the other address is in the same prefix subnet using the prefix length of this address.
It this address has no prefix length, returns false. The other address need not have an associated prefix length for this method to return true.
If this address string or the given address string is invalid, returns false.
other
- public boolean prefixContains(IPAddressString other)
prefixEquals(IPAddressString)
, but instead returns whether the prefix of this address contains the same of the given address,
using the prefix length of this address.
In other words, determines if the other address is in one of the same prefix subnets using the prefix length of this address.
It this address has no prefix length, returns false. The other address need not have an associated prefix length for this method to return true.
If this address string or the given address string is invalid, returns false.
other
- public boolean equals(Object o)
public boolean contains(IPAddressString other)
If this address string or the given address string is invalid then returns false.
other
- public IPAddress getHostAddress()
getAddress()
that incorporates the prefix.
Otherwise this returns the same object as getAddress()
.
This method returns null for invalid formats, the equivalent method toHostAddress()
throws exceptions for invalid formats.
public IPAddress getAddress(IPAddress.IPVersion version)
toAddress(inet.ipaddr.IPAddress.IPVersion)
, but returns null rather than throwing an exception with the address is invalid or does not match the supplied version.public IPAddress getAddress()
This method will return null for invalid formats. Use toAddress()
for an equivalent method that throws exceptions for invalid formats.
If you have a prefix address and you wish to get only the host without the prefix, use getHostAddress()
getAddress
in interface HostIdentifierString
public boolean isSequential()
When the IPAddressString is sequential, it can be represented exactly by the IPAddressSeqRange returned from getSequentialRange()
.
In some cases, no IPAddress instance can be obtained from getAddress()
or toAddress()
, in the cases where toAddress()
throws IncompatibleAddressException,
but if the IPAddressString is sequential, you can obtain a IPAddressSeqRange to represent the IPAddressString instead.
public IPAddressDivisionSeries getDivisionGrouping()
getAddress()
.
Examples of strings that do not have the standard segment counts and bit lengths include IPv6 addresses in mixed IPv6/IPv4 format, compressed IPv6 addresses, IPv6 addresses expressed as a single segment, IPv4 addresses in inet_aton form with fewer than 4 segments, and IPv4 or IPv6 addresses in which multiple segments are covered by the '*' wildcard.
The returned types is either IPAddressDivisionGrouping or IPAddressLargeDivisionGrouping in cases where one of the divisions is 64 bits or large.
This does not return instances of IPAddress, for that you should call getAddress()
or toAddress()
This can be useful for parsing formats that do not convert directly to a single instance of IPAddress, such as ranges of non-segmented IPv6 address values like aaaabbbbccccddddeeeeffffaaaabbb-ffffeeeeddddccccbbbbaaaabbbbaaaa, which in most cases cannot be converted to 8 ipv6 segment ranges and thus cannot be converted to a single IPAddress instance.
If the string used to construct this object is not a known format (empty string, address, range of addresses, or prefix) then null is returned.
If the string used to construct this object is a valid subnet format with a non-standard mask, and the masked result has divisions that are not sequential ranges, then null is returned.
An equivalent method that throws exceptions for invalid or incompatible formats is toDivisionGrouping()
public IPAddressSeqRange getSequentialRange()
Since not all IPAddressString instances describe a sequential series of addresses, this does not necessarily match the exact set of addresses specified by the string. For example, 1-2.3.4.1-2 produces the sequential range 1.3.4.1 to 2.3.4.2 that includes the address 1.255.255.2 not specified by the string.
The sequential range matches the same set of addresses as the address string or the address when isSequential()
is true.
Otherwise, the range includes addresses not specified by the address string.
This method can also produce a range for a string for which no IPAddress instance can be created,
those cases where isValid()
returns true but toAddress()
throws IncompatibleAddressException and getAddress()
returns null.
The range cannot be produced for the other cases where getAddress()
returns null, those that are version-ambiguous and do not throw IncompatibleAddressException,
such as the all address '*' or the version-ambiguous prefix length '/32'.
This is similar to toSequentialRange()
except that for invalid address strings, null is returned rather than throwing an exception.
public IPAddressDivisionSeries toDivisionGrouping() throws AddressStringException, IncompatibleAddressException
getAddress()
.
If the string used to construct this object is not a known format (empty string, address, range of addresses, or prefix) then this method throws AddressStringException
.
If the string used to construct this object is a valid subnet format with a non-standard mask, and the masked result has divisions that are not sequential ranges, then this method throws IncompatibleAddressException
.
An equivalent method that does not throw exceptions for invalid or incompatible formats is getDivisionGrouping()
Examples of strings that do not have the standard segment counts and bit lengths include IPv6 addresses in mixed IPv6/IPv4 format, compressed IPv6 addresses, IPv6 addresses expressed as a single segment, IPv4 addresses in inet_aton form with fewer than 4 segments, and IPv4 or IPv6 addresses in which multiple segments are covered by the '*' wildcard.
The returned type is either IPAddressDivisionGrouping or IPAddressLargeDivisionGrouping. It is IPAddressLargeDivisionGrouping in cases where one of the divisions is 64 bits or large.
This does not return instances of IPAddress, for that you should call getAddress()
or toAddress()
This can be useful for parsing formats that do not convert directly to a single instance of IPAddress, such as ranges of non-segmented IPv6 address values like aaaabbbbccccddddeeeeffffaaaabbb-ffffeeeeddddccccbbbbaaaabbbbaaaa, which in most cases cannot be converted to 8 ipv6 segment ranges and thus cannot be converted to a single IPAddress instance.
AddressStringException
IncompatibleAddressException
public IPAddressSeqRange toSequentialRange() throws AddressStringException
Since not all IPAddressString instances describe a sequential series of addresses, this does not necessarily match the exact set of addresses listed by the string. For example, 1-2.3.4.1-2 produces the sequential range 1.3.4.1 to 2.3.4.2 that includes the address 1.255.255.2 not specified by the string.
The sequential range matches the same set of addresses as the address string or the address when isSequential()
is true.
Otherwise, the range includes addresses not specified by the address string.
This method can also produce a range for a string for which no IPAddress instance can be created. This method does not throw IncompatibleAddressException.
This method does not throw for those cases where isValid()
returns true but toAddress()
throws IncompatibleAddressException and getAddress()
returns null.
There are some cases where this method returns null. The range cannot be produced for the other cases where getAddress()
returns null, those that are version-ambiguous and do not throw IncompatibleAddressException,
such as the all address '*' or the version-ambiguous prefix '/32'.
Keep in mind that all single addresses, all subnets using written in the canonical address formats, and all subnets with standard network or host masks, all of these have an associated IPAddress instance.
The exceptional cases are those subnets represented in formats supported by IPAddressString that cannot be represented in the canonical formats but can be . This includes IPv6 mixed address subnets that cannot be converted to canonical IPv6 format like ::0-1.2.0-1.4, subnets with non-standard masks like 0-2.2.3.4/2.0.0.0, and subnets represented with non-canonical segments like the IPv4 subnet 1.5000-6000 or the IPv6 subnet 1234567890abcdef1234567890abcdef-1234567890abcdef1234567890abcdef.
This method is equivalent to getSequentialRange()
except that for invalid address string formats, AddressStringException is thrown by this method.
AddressStringException
public IPAddress toHostAddress() throws AddressStringException, IncompatibleAddressException
toAddress()
.
Otherwise this returns the same object as toAddress()
.
This method throws exceptions for invalid formats, the equivalent method getHostAddress()
will simply return null in such cases.
If this instance of IPAddressString did not originate from a string, but from an IPAddress, then this will return an address that parses from a string to the same IPAddress (with prefix length added to the string if necessary to match).
This method is is intended to operate on the string that is wrapped by IPAddressString (visible from toString()
)
AddressStringException
IncompatibleAddressException
public IPAddress toAddress(IPAddress.IPVersion version) throws AddressStringException, IncompatibleAddressException
IPAddress
of the specified address version corresponding to this IPAddressString.
In most cases the string indicates the address version and calling toAddress()
is sufficient, with a few exceptions.
When this object represents only a network prefix length, specifying the address version allows the conversion to take place to the associated mask for that prefix length.
When this object represents all addresses, specifying the address version allows the conversion to take place to the associated representation of all IPv4 or all IPv6 addresses.
When this object represents the empty string and that string is interpreted as a loopback, then it returns the corresponding loopback address. If empty strings are not interpreted as loopback, null is returned.
When this object represents an ipv4 or ipv6 address, it returns that address if and only if that address matches the provided version.
If the string used to construct this object is an invalid format,
or a format that does not match the provided version, then this method throws AddressStringException
.
version
- the address version that this address should represent.AddressStringException
IncompatibleAddressException
- address in proper format cannot be converted to an address: for masks inconsistent with associated address range, or ipv4 mixed segments that cannot be joined into ipv6 segmentspublic IPAddress toAddress() throws AddressStringException, IncompatibleAddressException
IPAddress
corresponding to this IPAddressString.
If this object does not represent a specific IPAddress or a ranged IPAddress, null is returned, which may be the case if this object represents only a network prefix or if it represents the empty address string.
If the string used to construct this object is not a known format (empty string, address, range of addresses, or prefix) then this method throws AddressStringException
.
An equivalent method that does not throw exception for invalid formats is getAddress()
If you have a prefixed address and you wish to get only the host rather than the address with the prefix, use toHostAddress()
As long as this object represents a valid address (but not necessarily a specific address), this method does not throw.
toAddress
in interface HostIdentifierString
AddressStringException
- if the address format is invalidIncompatibleAddressException
- if a valid address string representing multiple addresses cannot be representedpublic IPAddressString adjustPrefixBySegment(boolean nextSegment)
This acts on address strings with an associated prefix length, whether or not there is also an associated address value, see isPrefixOnly()
.
If there is no associated address value then the segment boundaries are considered to be at each byte, much like IPv4.
If the address string has prefix length 0 and represents all addresses of the same version, and the prefix length is being decreased, then the address representing all addresses of any version is returned.
Follows the same rules as adjustPrefixLength(int)
when there is an associated address value:
When prefix length is increased, the bits moved within the prefix become zero.
When a prefix length is decreased, the bits moved outside the prefix become zero.
Also see IPAddress.adjustPrefixBySegment(boolean)
nextSegment
- whether to move prefix to previous or following segment boundarypublic IPAddressString adjustPrefixLength(int adjustment)
This acts on address strings with an associated prefix length, whether or not there is also an associated address value.
If the address string has prefix length 0 and represents all addresses of the same version, and the prefix length is being decreased, then the address representing all addresses of any version is returned.
When there is an associated address value and the prefix length is increased, the bits moved within the prefix become zero,
and if prefix length is extended beyond the segment series boundary, it is removed.
When there is an associated address value
and the prefix length is decreased, the bits moved outside the prefix become zero.
Also see IPAddress.adjustPrefixLength(int)
adjustment
- public static int countDelimitedAddresses(String str)
For example, given "1,2.3.4,5.6" this method will return 4 for the possible combinations: "1.3.4.6", "1.3.5.6", "2.3.4.6" and "2.3.5.6"
str
- public static Iterator<String> parseDelimitedSegments(String str)
For example, given "1,2.3.4,5.6" this will iterate through "1.3.4.6", "1.3.5.6", "2.3.4.6" and "2.3.5.6"
Another example: "1-2,3.4.5.6" will iterate through "1-2.4.5.6" and "1-3.4.5.6".
This method will not validate strings. Each string produced can be validated using an instance of IPAddressString.
str
- public String convertToPrefixLength() throws AddressStringException
AddressStringException
- if the address is invalidpublic String toNormalizedString()
HostIdentifierString
toNormalizedString
in interface HostIdentifierString
public String toString()
getAddress()
/toAddress()
and then use string methods on the address object.toString
in interface HostIdentifierString
toString
in class Object