Coverage Summary for Class: InetAddressBlock (co.rsk.scoring)
Class |
Class, %
|
Method, %
|
Line, %
|
InetAddressBlock |
0%
(0/1)
|
0%
(0/7)
|
0%
(0/31)
|
1 package co.rsk.scoring;
2
3 import com.google.common.annotations.VisibleForTesting;
4
5 import java.net.InetAddress;
6 import java.util.Arrays;
7
8 /**
9 * InetAddressBlock represents a range of InetAddress
10 * it has a number of bits to ignore
11 * <p>
12 * Created by ajlopez on 11/07/2017.
13 */
14 public class InetAddressBlock {
15 private final String description;
16 private final byte[] bytes;
17 private final int nbytes;
18 private final byte mask;
19
20 /**
21 * Creates an InetAddressBlock given an address and the number of bits to ignore
22 *
23 * @param address the address
24 * @param bits the numbers of bits to ignore
25 */
26 public InetAddressBlock(InetAddress address, int bits) {
27 this.description = address.getHostAddress() + "/" + bits;
28 this.bytes = address.getAddress();
29 this.nbytes = this.bytes.length - (bits + 7) / 8;
30 this.mask = (byte)(0xff << (bits % 8));
31 }
32
33 /**
34 * Returns if a given address is included or not in the address block
35 *
36 * @param address the address to check
37 * @return <tt>true</tt> if the address belongs to the address range
38 */
39 public boolean contains(InetAddress address) {
40 byte[] addressBytes = address.getAddress();
41
42 if (addressBytes.length != this.bytes.length) {
43 return false;
44 }
45
46 int k;
47
48 for (k = 0; k < this.nbytes; k++) {
49 if (addressBytes[k] != this.bytes[k]) {
50 return false;
51 }
52 }
53
54 if (this.mask != (byte)0xff) {
55 return (addressBytes[k] & this.mask) == (this.bytes[k] & this.mask);
56 }
57
58 return true;
59 }
60
61 /**
62 * Returns the string representation of the address block
63 *
64 * @return the string description of this block
65 * ie "192.168.51.1/16"
66 */
67 public String getDescription() {
68 return this.description;
69 }
70
71 @Override
72 public int hashCode() {
73 int result = 0;
74
75 for (int k = 0; k < this.bytes.length; k++) {
76 result *= 17;
77 result += this.bytes[k];
78 }
79
80 result *= 17;
81 result += this.mask;
82
83 return result;
84 }
85
86 @Override
87 public boolean equals(Object obj) {
88 if (obj == null) {
89 return false;
90 }
91
92 if (!(obj instanceof InetAddressBlock)) {
93 return false;
94 }
95
96 InetAddressBlock block = (InetAddressBlock)obj;
97
98 return block.mask == this.mask && Arrays.equals(block.bytes, this.bytes);
99 }
100
101 @VisibleForTesting
102 public byte[] getBytes() {
103 return this.bytes.clone();
104 }
105
106 @VisibleForTesting
107 public byte getMask() {
108 return this.mask;
109 }
110 }