1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.bremersee.security;
18
19 import java.net.InetAddress;
20 import java.net.UnknownHostException;
21 import org.springframework.util.Assert;
22 import org.springframework.util.StringUtils;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 public class IpAddressMatcher {
38
39 private final int numMaskBits;
40
41 private final InetAddress requiredAddress;
42
43
44
45
46
47
48 public IpAddressMatcher(String ipAddress) {
49
50 if (ipAddress.indexOf('/') > 0) {
51 String[] addressAndMask = StringUtils.split(ipAddress, "/");
52
53 ipAddress = addressAndMask[0];
54 numMaskBits = Integer.parseInt(addressAndMask[1]);
55 } else {
56 numMaskBits = -1;
57 }
58 requiredAddress = parseAddress(ipAddress);
59 Assert.isTrue(requiredAddress.getAddress().length * 8 >= numMaskBits,
60 String.format("IP address %s is too short for bitmask of length %d",
61 ipAddress, numMaskBits));
62 }
63
64
65
66
67
68
69
70 public boolean matches(String address) {
71 InetAddress remoteAddress = parseAddress(address);
72
73 if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
74 return false;
75 }
76
77 if (numMaskBits < 0) {
78 return remoteAddress.equals(requiredAddress);
79 }
80
81 byte[] remAddr = remoteAddress.getAddress();
82 byte[] reqAddr = requiredAddress.getAddress();
83
84 int numMaskFullBytes = numMaskBits / 8;
85 byte finalByte = (byte) (0xFF00 >> (numMaskBits & 0x07));
86
87
88
89 for (int i = 0; i < numMaskFullBytes; i++) {
90 if (remAddr[i] != reqAddr[i]) {
91 return false;
92 }
93 }
94
95 if (finalByte != 0) {
96 return (remAddr[numMaskFullBytes] & finalByte) == (reqAddr[numMaskFullBytes] & finalByte);
97 }
98
99 return true;
100 }
101
102 private InetAddress parseAddress(String address) {
103 try {
104 return InetAddress.getByName(address);
105 } catch (UnknownHostException e) {
106 throw new IllegalArgumentException("Failed to parse address" + address, e);
107 }
108 }
109 }