16 package org.openkilda.testing.service.traffexam.networkpool;
18 import java.net.Inet4Address;
19 import java.net.UnknownHostException;
22 private Inet4Address network;
28 this.checkPrefix(prefix, (byte) 0);
29 this.prefix = (byte) prefix;
31 this.mask = this.makeMask(this.prefix);
32 this.network = this.
applyMask(network, this.mask);
40 this.checkPrefix(prefix, prefix);
42 index <<= 32 - prefix;
44 this.checkOverflow(
target);
54 this.checkOverflow(
target);
65 byte[] unpacked =
address.getAddress();
67 for (
int idx = 0; idx < unpacked.length; idx++) {
68 unpacked[idx] &= mask[idx];
72 return (Inet4Address) Inet4Address.getByAddress(unpacked);
73 }
catch (UnknownHostException e) {
74 throw new Inet4ValueException(
"Unable to \"pack\" raw address.", e);
78 private byte[] makeMask(
int prefix) {
79 byte[] mask =
new byte[4];
81 int shift = 32 - prefix;
82 for (
int idx = 0; idx < mask.length; idx++, shift -= 8) {
87 mask[mask.length - 1 - idx] = (byte) (blank & 0xff);
93 private Inet4Address merge(
long add)
throws Inet4ValueException {
94 byte[] unpacked =
new byte[4];
96 for (
int idx = 0; idx < unpacked.length; idx++) {
97 unpacked[unpacked.length - 1 - idx] = (byte) (add & 0xff);
101 return this.merge(unpacked);
104 private Inet4Address merge(byte[] add)
throws Inet4ValueException {
105 byte[] unpacked = network.getAddress();
107 for (
int idx = 0; idx < unpacked.length; idx++) {
108 unpacked[idx] |= add[idx];
112 return (Inet4Address) Inet4Address.getByAddress(unpacked);
113 }
catch (UnknownHostException e) {
114 throw new Inet4ValueException(
"Unable to \"pack\" raw address.", e);
118 private void checkPrefix(
int prefix,
int lowest)
throws Inet4ValueException {
119 if (prefix < lowest || 32 < prefix) {
120 throw new Inet4ValueException(String.format(
121 "Invalid network prefix. Must be in range from %d to 32",
126 private void checkOverflow(Inet4Address subject)
throws Inet4ValueException {
127 if (!network.equals(
this.applyMask(subject))) {
128 throw new Inet4ValueException(
"Request address beyond network");
Inet4Address applyMask(Inet4Address address)
Inet4Address getNetwork()
Inet4Network(Inet4Address network, int prefix)
Inet4Network subnet(long index, int prefix)
Inet4Address address(long index)