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