1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package edu.internet2.middleware.shibboleth.idp.util;
18
19 import java.net.InetAddress;
20 import java.net.UnknownHostException;
21 import java.util.BitSet;
22
23 import org.opensaml.xml.util.DatatypeHelper;
24
25
26 public class IPRange {
27
28
29 private int addressLength;
30
31
32 private BitSet network;
33
34
35 private BitSet mask;
36
37
38
39
40
41
42
43 public IPRange(InetAddress networkAddress, int maskSize) {
44 this(networkAddress.getAddress(), maskSize);
45 }
46
47
48
49
50
51
52
53 public IPRange(byte[] networkAddress, int maskSize) {
54 addressLength = networkAddress.length * 8;
55 if (addressLength != 32 && addressLength != 128) {
56 throw new IllegalArgumentException("Network address was neither an IPv4 or IPv6 address");
57 }
58
59 network = toBitSet(networkAddress);
60 mask = new BitSet(addressLength);
61 mask.set(addressLength - maskSize, addressLength, true);
62 }
63
64
65
66
67
68
69
70
71 public static IPRange parseCIDRBlock(String cidrBlock){
72 String block = DatatypeHelper.safeTrimOrNullString(cidrBlock);
73 if(block == null){
74 throw new IllegalArgumentException("CIDR block definition may not be null");
75 }
76
77 String[] blockParts = block.split("/");
78 try{
79 InetAddress networkAddress = InetAddress.getByName(blockParts[0]);
80 int maskSize = Integer.parseInt(blockParts[1]);
81 return new IPRange(networkAddress, maskSize);
82 }catch(UnknownHostException e){
83 throw new IllegalArgumentException("Invalid IP address");
84 }catch(NumberFormatException e){
85 throw new IllegalArgumentException("Invalid netmask size");
86 }
87 }
88
89
90
91
92
93
94
95
96 public boolean contains(InetAddress address) {
97 return contains(address.getAddress());
98 }
99
100
101
102
103
104
105
106
107 public boolean contains(byte[] address) {
108 if (address.length * 8 != addressLength) {
109 return false;
110 }
111
112 BitSet addrNetwork = toBitSet(address);
113 addrNetwork.and(mask);
114
115 return addrNetwork.equals(network);
116 }
117
118
119
120
121
122
123
124
125
126
127 protected BitSet toBitSet(byte[] bytes) {
128 BitSet bits = new BitSet(bytes.length * 8);
129
130 for (int i = 0; i < bytes.length * 8; i++) {
131 if ((bytes[bytes.length - i / 8 - 1] & (1 << (i % 8))) > 0) {
132 bits.set(i);
133 }
134 }
135
136 return bits;
137 }
138 }