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