1 /*******************************************************************************
\r
2 * ============LICENSE_START====================================================
\r
4 * * ===========================================================================
\r
5 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
\r
6 * * ===========================================================================
\r
7 * * Licensed under the Apache License, Version 2.0 (the "License");
\r
8 * * you may not use this file except in compliance with the License.
\r
9 * * You may obtain a copy of the License at
\r
11 * * http://www.apache.org/licenses/LICENSE-2.0
\r
13 * * Unless required by applicable law or agreed to in writing, software
\r
14 * * distributed under the License is distributed on an "AS IS" BASIS,
\r
15 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
16 * * See the License for the specific language governing permissions and
\r
17 * * limitations under the License.
\r
18 * * ============LICENSE_END====================================================
\r
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
\r
22 ******************************************************************************/
\r
23 package org.onap.aaf.cadi.util;
\r
26 * NetMask - a class to quickly validate whether a given IP is part of a mask, as defined by bytes or standard String format.
\r
28 * Needs the IPV6 Mask Builder.
\r
30 public class NetMask {
\r
33 public NetMask(byte[] inBytes) {
\r
34 mask = derive(inBytes);
\r
37 public NetMask(String string) throws MaskFormatException {
\r
38 mask = derive(string,true);
\r
41 public boolean isInNet(byte[] inBytes) {
\r
42 long addr = derive(inBytes);
\r
43 return (mask & addr) == addr;
\r
46 public boolean isInNet(String str) {
\r
49 addr = derive(str,false);
\r
50 return (mask & addr) == addr;
\r
51 } catch (MaskFormatException e) {
\r
52 // will not hit this code;
\r
57 public static long derive(byte[] inBytes) {
\r
59 int offset = inBytes.length*8;
\r
60 for(int i=0;i<inBytes.length;++i) {
\r
61 addr&=(inBytes[i]<<offset);
\r
67 public static long derive(String str, boolean check) throws MaskFormatException {
\r
69 int idx=str.indexOf(':');
\r
70 int slash = str.indexOf('/');
\r
72 if(idx<0) { // Not IPV6, so it's IPV4... Is there a mask of 123/254?
\r
73 idx=str.indexOf('.');
\r
75 int end = slash>=0?slash:str.length();
\r
76 int bits = slash>=0?Integer.parseInt(str.substring(slash+1)):32;
\r
77 if(check && bits>32) {
\r
78 throw new MaskFormatException("Invalid Mask Offset in IPV4 Address");
\r
86 lbyte = Long.parseLong(str.substring(prev, idx));
\r
87 if(check && (lbyte>255 || lbyte<0)) {
\r
88 throw new MaskFormatException("Invalid Byte in IPV4 Address");
\r
92 idx=str.indexOf('.',prev);
\r
95 rv|=0x00000000FFFFFFFFL>>bits;
\r