1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.access.mcrimpl;
20
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.Arrays;
24 import java.util.stream.IntStream;
25
26 import org.mycore.common.MCRException;
27
28
29
30
31
32
33 public class MCRIPAddress {
34 byte[] address;
35
36 byte[] mask;
37
38 public MCRIPAddress(String ip) throws UnknownHostException {
39 int i = ip.indexOf('/');
40
41 if (i >= 0) {
42 String ipstr = ip.substring(0, i);
43 String maskstr = ip.substring(i + 1);
44 InetAddress address = InetAddress.getByName(ipstr);
45 InetAddress mask = InetAddress.getByName(maskstr);
46 init(address, mask);
47 } else {
48 InetAddress address = InetAddress.getByName(ip);
49 init(address);
50 }
51 }
52
53 public MCRIPAddress(InetAddress address, InetAddress mask) {
54 init(address, mask);
55 }
56
57 public MCRIPAddress(InetAddress address) {
58 init(address);
59 }
60
61 public void init(InetAddress address, InetAddress mask) {
62 this.address = address.getAddress();
63 this.mask = mask.getAddress();
64 }
65
66 public void init(InetAddress address) {
67 this.address = address.getAddress();
68 mask = new byte[this.address.length];
69 Arrays.fill(mask, (byte) 255);
70 }
71
72 public boolean contains(MCRIPAddress other) {
73 if (address.length != other.address.length) {
74 return false;
75 }
76
77 return IntStream.range(0, address.length)
78 .noneMatch(t -> (address[t] & mask[t]) != (other.address[t] & mask[t]));
79 }
80
81 public byte[] getAddress() {
82 return address;
83 }
84
85 @Override
86 public String toString() {
87 try {
88 InetAddress inetAddress = InetAddress.getByAddress(address);
89 InetAddress maskAddress = InetAddress.getByAddress(mask);
90 StringBuilder sb = new StringBuilder();
91 sb.append(inetAddress.getHostAddress());
92 sb.append('/');
93 sb.append(maskAddress.getHostAddress());
94 return sb.toString();
95 } catch (UnknownHostException e) {
96 throw new MCRException(e);
97 }
98
99 }
100 }