1 | /** |
2 | * Licensed to jclouds, Inc. (jclouds) under one or more |
3 | * contributor license agreements. See the NOTICE file |
4 | * distributed with this work for additional information |
5 | * regarding copyright ownership. jclouds licenses this file |
6 | * to you under the Apache License, Version 2.0 (the |
7 | * "License"); you may not use this file except in compliance |
8 | * with the License. You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, |
13 | * software distributed under the License is distributed on an |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
15 | * KIND, either express or implied. See the License for the |
16 | * specific language governing permissions and limitations |
17 | * under the License. |
18 | */ |
19 | package org.jclouds.util; |
20 | |
21 | import static com.google.common.base.Preconditions.checkNotNull; |
22 | |
23 | import javax.inject.Singleton; |
24 | |
25 | import com.google.common.base.Predicate; |
26 | import com.google.common.base.Splitter; |
27 | import com.google.common.collect.Iterables; |
28 | import com.google.common.net.InetAddresses; |
29 | |
30 | /** |
31 | * |
32 | * |
33 | * @author Adrian Cole |
34 | */ |
35 | public class InetAddresses2 { |
36 | @Singleton |
37 | public static enum IsPrivateIPAddress implements Predicate<String> { |
38 | INSTANCE; |
39 | |
40 | public boolean apply(String in) { |
41 | if (InetAddresses.isInetAddress(checkNotNull(in, "input address"))) { |
42 | // 24-bit Block (/8 prefix, 1/A) 10.0.0.0 10.255.255.255 16777216 |
43 | if (in.indexOf("10.") == 0) |
44 | return true; |
45 | // 20-bit Block (/12 prefix, 16/B) 172.16.0.0 172.31.255.255 1048576 |
46 | if (in.indexOf("172.") == 0) { |
47 | int second = Integer.parseInt(Iterables.get(Splitter.on('.').split(in), 1)); |
48 | if (second >= 16 && second <= 31) |
49 | return true; |
50 | } |
51 | // 16-bit Block (/16 prefix, 256/C) 192.168.0.0 192.168.255.255 65536 |
52 | if (in.indexOf("192.168.") == 0) |
53 | return true; |
54 | } |
55 | return false; |
56 | } |
57 | |
58 | @Override |
59 | public String toString() { |
60 | return "isPrivateIPAddress()"; |
61 | } |
62 | |
63 | } |
64 | |
65 | /** |
66 | * @return true if the input is an ip4 address and in one of the 3 reserved private blocks. |
67 | */ |
68 | public static boolean isPrivateIPAddress(String in) { |
69 | return IsPrivateIPAddress.INSTANCE.apply(in); |
70 | } |
71 | |
72 | } |