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