summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/config/InetAddresses.java
blob: 989598da0ab457aec64eddf48d8a16153e8276ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright © 2017-2018 WireGuard LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

package com.wireguard.config;

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);
        }
    }

    private InetAddresses() {
        // Prevent instantiation.
    }

    /**
     * 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) {
            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);
        }
    }
}