Do not do DNS lookups for IPs

This involves reflection, which is a bummer, but it's better than doing
unnecessary DNS lookups.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld
2018-04-27 18:34:52 +02:00
parent 9c6f9135e9
commit 693228985d
4 changed files with 29 additions and 14 deletions
@@ -2,6 +2,9 @@ package com.wireguard.config;
import android.text.TextUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -54,6 +57,30 @@ enum Attribute {
return string.trim().split("\\s*,\\s*");
}
private static Method parseNumericAddressMethod;
static {
try {
parseNumericAddressMethod = InetAddress.class.getMethod("parseNumericAddress", new Class[]{String.class});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static InetAddress parseIPString(final String address) {
if (address == null || address.isEmpty())
throw new IllegalArgumentException("Empty address");
try {
return (InetAddress)parseNumericAddressMethod.invoke(null, new Object[]{address});
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof IllegalArgumentException)
throw (IllegalArgumentException)e.getCause();
else
throw new IllegalArgumentException(e.getCause());
}
}
public String composeWith(final Object value) {
return String.format("%s = %s%n", token, value);
}