diff options
Diffstat (limited to 'app/src/main/java/com/wireguard/config/InetAddresses.java')
-rw-r--r-- | app/src/main/java/com/wireguard/config/InetAddresses.java | 29 |
1 files changed, 20 insertions, 9 deletions
diff --git a/app/src/main/java/com/wireguard/config/InetAddresses.java b/app/src/main/java/com/wireguard/config/InetAddresses.java index c50c5a0e..989598da 100644 --- a/app/src/main/java/com/wireguard/config/InetAddresses.java +++ b/app/src/main/java/com/wireguard/config/InetAddresses.java @@ -5,21 +5,22 @@ package com.wireguard.config; -import android.support.annotation.Nullable; - -import com.wireguard.android.Application; -import com.wireguard.android.R; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.net.Inet4Address; +import java.net.Inet6Address; import java.net.InetAddress; +/** + * Utility methods for creating instances of {@link InetAddress}. + */ public final class InetAddresses { private static final Method PARSER_METHOD; static { try { // This method is only present on Android. + // noinspection JavaReflectionMemberAccess PARSER_METHOD = InetAddress.class.getMethod("parseNumericAddress", String.class); } catch (final NoSuchMethodException e) { throw new RuntimeException(e); @@ -30,13 +31,23 @@ public final class InetAddresses { // Prevent instantiation. } - public static InetAddress parse(@Nullable final String address) { - if (address == null || address.isEmpty()) - throw new IllegalArgumentException(Application.get().getString(R.string.tunnel_error_empty_inetaddress)); + /** + * Parses a numeric IPv4 or IPv6 address without performing any DNS lookups. + * + * @param address a string representing the IP address + * @return an instance of {@link Inet4Address} or {@link Inet6Address}, as appropriate + */ + public static InetAddress parse(final String address) { + if (address.isEmpty()) + throw new IllegalArgumentException("Empty address"); try { return (InetAddress) PARSER_METHOD.invoke(null, address); } catch (final IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e.getCause() == null ? e : e.getCause()); + final Throwable cause = e.getCause(); + // Re-throw parsing exceptions with the original type, as callers might try to catch + // them. On the other hand, callers cannot be expected to handle reflection failures. + throw cause instanceof IllegalArgumentException ? + (IllegalArgumentException) cause : new RuntimeException(e); } } } |