Package uk.ipfreely

Class Subnets<A extends Address<A>>

java.lang.Object
uk.ipfreely.Subnets<A>
Type Parameters:
A - address type

public final class Subnets<A extends Address<A>> extends Object
Provides utility methods for working with RFC-4632 Classless Inter-domain Routing blocks of IP addresses for a given Family. Obtain instances from Family.subnets().
  • Method Details

    • family

      public Family<A> family()
      IP address family.
      Returns:
      Family.v4() or Family.v6()
    • masks

      public List<A> masks()

      All possible IP address masks for this family. The masks are indexed by mask size.

      For IPv4 index 0 is /0 "0.0.0.0", index 1 is /1 "128.0.0.0", and index 32 is /32 "255.255.255.255".

      For IPv6 index 0 is /0 "::" and index 128 is /128 "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff".

      Returns:
      immutable list of possible network address masks
    • maskBits

      public int maskBits(A first, A last)

      Calculates the mask bit size for an IP address CIDR block range. The first argument MUST be less than or equal to the last.

      For "172.0.0.0" and "172.255.255.255" forming block "172.0.0.0/8" this will return 8.

      The return value can be used as the mask index for masks(). Valid mask sizes are from zero to Family.width() inclusive.

      -1 is returned if the arguments do not form a valid block.

      
           // EXAMPLE
           V4 first = Family.v4().parse("127.0.0.0");
           V4 last = Family.v4().parse("127.255.255.255");
           Subnets<V4> subnets = Family.v4().subnets();
           // 8
           int maskBits = subnets.maskBits(first, last);
           // 255.0.0.0
           V4 mask = subnets.masks().get(maskBits);
       
      Parameters:
      first - the first element in an IP range
      last - the last element in an IP range
      Returns:
      mask size in bits or -1 if arguments not a valid CIDR block
    • count

      public BigInteger count(int maskBits)
      The number of addresses for the number of bits in a CIDR notation mask. Use maskAddressCount(0) to get the number of IP addresses in this family.
      
           // EXAMPLE
           int maskBits = 22;
           V4 network = Family.v4().parse("10.9.0.0");
           V4 mask = Family.v4().subnets().masks().get(maskBits);
           BigInteger addresses = Family.v4().subnets().count(maskBits);
           // "10.9.0.0/22 has 1024 addresses and mask 255.255.252.0"
           String description = network + "/" + maskBits + " has " + addresses + " addresses and mask " + mask;
       
      Parameters:
      maskBits - between 0 and the family width in bits (inclusive)
      Returns:
      the count of addresses for a given subnet size
      See Also:
    • toString

      public String toString()
      Informational.
      Overrides:
      toString in class Object
      Returns:
      IP family version