From b9991e4229b49e08beebbae5519cfed5de99c051 Mon Sep 17 00:00:00 2001 From: Samuel Holland Date: Tue, 19 Jun 2018 00:43:49 -0500 Subject: 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 --- .../java/com/wireguard/config/InetNetwork.java | 61 ++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 app/src/main/java/com/wireguard/config/InetNetwork.java (limited to 'app/src/main/java/com/wireguard/config/InetNetwork.java') 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 + * Copyright © 2018 Jason A. Donenfeld . 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; + } +} -- cgit v1.2.3