blob: afc8ab3e234ef1f24ecbc4fb0b62813844c215e2 [file] [log] [blame]
Bob zhou59a21062016-05-12 19:40:05 +08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
Bob zhou59a21062016-05-12 19:40:05 +08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.vtn.util;
17
18import org.onlab.packet.IpAddress;
19
20/**
21 * IpUtil utility class.
22 */
23public final class IpUtil {
24
25 private IpUtil() {
26 }
27
28 /**
29 * check source Ip and destination Ip in same Subnet.
30 *
31 * @param srcIp source Ip
32 * @param dstIp destination
Avantika-Huawei09a6a2e2016-05-16 19:14:30 +053033 * @param mask netmask length
Bob zhou59a21062016-05-12 19:40:05 +080034 * @return boolean
35 */
36 public static boolean checkSameSegment(IpAddress srcIp, IpAddress dstIp,
37 int mask) {
38 String[] ips = srcIp.toString().split("\\.");
39 int ipAddr = (Integer.parseInt(ips[0]) << 24)
40 | (Integer.parseInt(ips[1]) << 16)
41 | (Integer.parseInt(ips[2]) << 8)
42 | Integer.parseInt(ips[3]);
43 int netmask = 0xFFFFFFFF << (32 - mask);
44 String[] cidrIps = dstIp.toString().split("\\.");
45 int cidrIpAddr = (Integer.parseInt(cidrIps[0]) << 24)
46 | (Integer.parseInt(cidrIps[1]) << 16)
47 | (Integer.parseInt(cidrIps[2]) << 8)
48 | Integer.parseInt(cidrIps[3]);
49
50 return (ipAddr & netmask) == (cidrIpAddr & netmask);
51 }
52}