blob: c8a88290142f6e97c6da16f2f2424ceeb307e582 [file] [log] [blame]
jaegonkimdcf7c822019-02-06 15:00:14 +09001/*
2 * Copyright 2019-present Open Networking Foundation
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 */
16package org.onosproject.ofoverlay.impl.util;
17
18import com.google.common.base.MoreObjects;
19import org.onlab.packet.IpAddress;
20import org.onlab.packet.IpPrefix;
21
22import java.util.Objects;
23
24import static com.google.common.base.Preconditions.checkArgument;
25
26/**
27 * Representation of a network address, which consists of IP address and prefix.
28 */
29public final class NetworkAddress {
30 private final IpAddress ip;
31 private final IpPrefix prefix;
32
33 /**
34 * Constructor for a given IP address and prefix.
35 *
36 * @param ip ip address
37 * @param prefix ip prefix
38 */
39 private NetworkAddress(IpAddress ip, IpPrefix prefix) {
40 this.ip = ip;
41 this.prefix = prefix;
42 }
43
44 /**
45 * Converts a CIDR notation string into a network address.
46 *
47 * @param cidr cidr
48 * @return network address
49 * @throws IllegalArgumentException if the cidr is not valid
50 */
51 public static NetworkAddress valueOf(String cidr) {
52 checkArgument(cidr.contains("/"));
53
54 IpAddress ipAddress = IpAddress.valueOf(cidr.split("/")[0]);
55 IpPrefix ipPrefix = IpPrefix.valueOf(cidr);
56
57 return new NetworkAddress(ipAddress, ipPrefix);
58 }
59
60 /**
61 * Returns the IP address value of the network address.
62 *
63 * @return ip address
64 */
65 public IpAddress ip() {
66 return this.ip;
67 }
68
69 /**
70 * Returns the IP prefix value of the network address.
71 *
72 * @return ip prefix
73 */
74 public IpPrefix prefix() {
75 return this.prefix;
76 }
77
78 /**
79 * Converts a network address to a CIDR notation.
80 *
81 * @return cidr notation string
82 */
83 public String cidr() {
84 return ip.toString() + "/" + prefix.prefixLength();
85 }
86
87 @Override
88 public boolean equals(Object obj) {
89 if (this == obj) {
90 return true;
91 }
92
93 if (obj instanceof NetworkAddress) {
94 NetworkAddress that = (NetworkAddress) obj;
95 return Objects.equals(ip, that.ip) && Objects.equals(prefix, that.prefix);
96 }
97 return false;
98 }
99
100 @Override
101 public int hashCode() {
102 return Objects.hash(ip, prefix);
103 }
104
105 @Override
106 public String toString() {
107 return MoreObjects.toStringHelper(getClass())
108 .add("IpAddress", ip)
109 .add("IpPrefix", prefix)
110 .toString();
111 }
112}