1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.mina.filter.firewall;
22
23 import java.net.Inet4Address;
24 import java.net.InetAddress;
25
26
27
28
29
30
31
32 public class Subnet {
33
34 private static final int IP_MASK_V4 = 0x80000000;
35
36 private static final long IP_MASK_V6 = 0x8000000000000000L;
37
38 private static final int BYTE_MASK = 0xFF;
39
40 private InetAddress subnet;
41
42
43 private int subnetInt;
44
45
46 private long subnetLong;
47
48 private long subnetMask;
49
50 private int suffix;
51
52
53
54
55
56
57
58
59 public Subnet(InetAddress subnet, int mask) {
60 if (subnet == null) {
61 throw new IllegalArgumentException("Subnet address can not be null");
62 }
63
64 if (!(subnet instanceof Inet4Address)) {
65 throw new IllegalArgumentException("Only IPv4 supported");
66 }
67
68 if (subnet instanceof Inet4Address) {
69
70 if ((mask < 0) || (mask > 32)) {
71 throw new IllegalArgumentException("Mask has to be an integer between 0 and 32 for an IPV4 address");
72 } else {
73 this.subnet = subnet;
74 subnetInt = toInt(subnet);
75 this.suffix = mask;
76
77
78 this.subnetMask = IP_MASK_V4 >> (mask - 1);
79 }
80 } else {
81
82 if ((mask < 0) || (mask > 128)) {
83 throw new IllegalArgumentException("Mask has to be an integer between 0 and 128 for an IPV6 address");
84 } else {
85 this.subnet = subnet;
86 subnetLong = toLong(subnet);
87 this.suffix = mask;
88
89
90 this.subnetMask = IP_MASK_V6 >> (mask - 1);
91 }
92 }
93 }
94
95
96
97
98 private int toInt(InetAddress inetAddress) {
99 byte[] address = inetAddress.getAddress();
100 int result = 0;
101
102 for (int i = 0; i < address.length; i++) {
103 result <<= 8;
104 result |= address[i] & BYTE_MASK;
105 }
106
107 return result;
108 }
109
110
111
112
113 private long toLong(InetAddress inetAddress) {
114 byte[] address = inetAddress.getAddress();
115 long result = 0;
116
117 for (int i = 0; i < address.length; i++) {
118 result <<= 8;
119 result |= address[i] & BYTE_MASK;
120 }
121
122 return result;
123 }
124
125
126
127
128
129
130
131
132 private long toSubnet(InetAddress address) {
133 if (address instanceof Inet4Address) {
134 return toInt(address) & (int) subnetMask;
135 } else {
136 return toLong(address) & subnetMask;
137 }
138 }
139
140
141
142
143
144
145 public boolean inSubnet(InetAddress address) {
146 if (address.isAnyLocalAddress()) {
147 return true;
148 }
149
150 if (address instanceof Inet4Address) {
151 return (int) toSubnet(address) == subnetInt;
152 } else {
153 return toSubnet(address) == subnetLong;
154 }
155 }
156
157
158
159
160 @Override
161 public String toString() {
162 return subnet.getHostAddress() + "/" + suffix;
163 }
164
165 @Override
166 public boolean equals(Object obj) {
167 if (!(obj instanceof Subnet)) {
168 return false;
169 }
170
171 Subnet other = (Subnet) obj;
172
173 return other.subnetInt == subnetInt && other.suffix == suffix;
174 }
175
176 }