public final class NetMask extends Object
The constructor takes a string as an argument which represents a netmask, as
per the CIDR notation -- whether this netmask be IPv4 or IPv6. It then
extracts the network address (before the /) and the CIDR prefix (after the
/), and tells through the #matches() method whether a candidate
InetAddress
object fits in the recorded range.
As byte arrays as returned by InetAddress.getByName()
are always
in network byte order, finding a match is therefore as simple as testing
whether the n first bits (where n is the CIDR) are the same in both byte
arrays (the one of the network address and the one of the candidate address).
We do that by first doing byte comparisons, then testing the last bits if any
(that is, if the remainder of the integer division of the CIDR by 8 is not
0).
As a bonus, if no '/' is found in the input, it is assumed that an exact address match is required.
public NetMask(String input)
input
- the CIDR netmaskIllegalArgumentException
- if the netmask is not correct (invalid
address specification, malformed CIDR prefix, etc)public boolean matches(InetAddress addr)
addr
- The InetAddress
to testCopyright © 2000-2021 Apache Software Foundation. All Rights Reserved.