Bob zhou | 59a2106 | 2016-05-12 19:40:05 +0800 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2016-present Open Networking Foundation |
Bob zhou | 59a2106 | 2016-05-12 19:40:05 +0800 | [diff] [blame] | 3 | * |
| 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 | */ |
| 16 | package org.onosproject.vtn.util; |
| 17 | |
| 18 | import org.onlab.packet.IpAddress; |
| 19 | |
| 20 | /** |
| 21 | * IpUtil utility class. |
| 22 | */ |
| 23 | public 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-Huawei | 09a6a2e | 2016-05-16 19:14:30 +0530 | [diff] [blame] | 33 | * @param mask netmask length |
Bob zhou | 59a2106 | 2016-05-12 19:40:05 +0800 | [diff] [blame] | 34 | * @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 | } |