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
33 public class Subnet {
34
35 private static final int IP_MASK = 0x80000000;
36 private static final int BYTE_MASK = 0xFF;
37
38 private InetAddress subnet;
39 private int subnetInt;
40 private int subnetMask;
41 private int suffix;
42
43
44
45
46
47
48
49
50 public Subnet(InetAddress subnet, int mask) {
51 if(subnet == null) {
52 throw new NullPointerException("Subnet address can not be null");
53 }
54 if(!(subnet instanceof Inet4Address)) {
55 throw new IllegalArgumentException("Only IPv4 supported");
56 }
57
58 if(mask < 0 || mask > 32) {
59 throw new IllegalArgumentException("Mask has to be an integer between 0 and 32");
60 }
61
62 this.subnet = subnet;
63 this.subnetInt = toInt(subnet);
64 this.suffix = mask;
65
66
67 this.subnetMask = IP_MASK >> (mask - 1);
68 }
69
70
71
72
73 private int toInt(InetAddress inetAddress) {
74 byte[] address = inetAddress.getAddress();
75 int result = 0;
76 for (int i = 0; i < address.length; i++) {
77 result <<= 8;
78 result |= address[i] & BYTE_MASK;
79 }
80 return result;
81 }
82
83
84
85
86
87
88
89 private int toSubnet(InetAddress address) {
90 return toInt(address) & subnetMask;
91 }
92
93
94
95
96
97
98 public boolean inSubnet(InetAddress address) {
99 return toSubnet(address) == subnetInt;
100 }
101
102
103
104
105 @Override
106 public String toString() {
107 return subnet.getHostAddress() + "/" + suffix;
108 }
109
110 @Override
111 public boolean equals(Object obj) {
112 if(!(obj instanceof Subnet)) {
113 return false;
114 }
115
116 Subnet other = (Subnet) obj;
117
118 return other.subnetInt == subnetInt && other.suffix == suffix;
119 }
120
121
122 }