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