summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/config/InetNetwork.java
diff options
context:
space:
mode:
authorSamuel Holland <samuel@sholland.org>2018-06-19 00:43:49 -0500
committerSamuel Holland <samuel@sholland.org>2018-06-19 21:59:44 -0500
commitb9991e4229b49e08beebbae5519cfed5de99c051 (patch)
tree4a233404b0b910539b149fbbda97f689ec31d6bc /app/src/main/java/com/wireguard/config/InetNetwork.java
parent4acee49d4b0da6273cd9ffef1573185f955b5774 (diff)
config: Refactor IPCidr and use of InetAddress
Use a canonically-named utility class to tack on methods to the existing InetAddress class. Rename IPCidr to InetNetwork so it better matches InetAddress and is more pronouceable :) While here, simplify the constructor and toString() functions, and properly implement hashCode(). Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Diffstat (limited to 'app/src/main/java/com/wireguard/config/InetNetwork.java')
-rw-r--r--app/src/main/java/com/wireguard/config/InetNetwork.java61
1 files changed, 61 insertions, 0 deletions
diff --git a/app/src/main/java/com/wireguard/config/InetNetwork.java b/app/src/main/java/com/wireguard/config/InetNetwork.java
new file mode 100644
index 00000000..27825e6a
--- /dev/null
+++ b/app/src/main/java/com/wireguard/config/InetNetwork.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright © 2018 Samuel Holland <samuel@sholland.org>
+ * Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+package com.wireguard.config;
+
+import android.support.annotation.NonNull;
+
+import java.net.Inet4Address;
+import java.net.InetAddress;
+import java.util.Objects;
+
+public class InetNetwork {
+ private final InetAddress address;
+ private final int mask;
+
+ public InetNetwork(@NonNull final String input) {
+ final int slash = input.lastIndexOf('/');
+ final int rawMask;
+ final String rawAddress;
+ if (slash >= 0) {
+ rawMask = Integer.parseInt(input.substring(slash + 1), 10);
+ rawAddress = input.substring(0, slash);
+ } else {
+ rawMask = -1;
+ rawAddress = input;
+ }
+ address = InetAddresses.parse(rawAddress);
+ final int maxMask = (address instanceof Inet4Address) ? 32 : 128;
+ mask = rawMask >= 0 && rawMask <= maxMask ? rawMask : maxMask;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (!(obj instanceof InetNetwork))
+ return false;
+ final InetNetwork other = (InetNetwork) obj;
+ return Objects.equals(address, other.address) && mask == other.mask;
+ }
+
+ @NonNull
+ public InetAddress getAddress() {
+ return address;
+ }
+
+ public int getMask() {
+ return mask;
+ }
+
+ @Override
+ public int hashCode() {
+ return address.hashCode() ^ mask;
+ }
+
+ @Override
+ public String toString() {
+ return address.getHostAddress() + '/' + mask;
+ }
+}