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