summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/config/InetAddresses.java
blob: c50c5a0e1dff3d1cb353520dda70320b758a1b22 (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
/*
 * Copyright © 2017-2018 WireGuard LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

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.InetAddress;

public final class InetAddresses {
    private static final Method PARSER_METHOD;

    static {
        try {
            // This method is only present on Android.
            PARSER_METHOD = InetAddress.class.getMethod("parseNumericAddress", String.class);
        } catch (final NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    private 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));
        try {
            return (InetAddress) PARSER_METHOD.invoke(null, address);
        } catch (final IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e.getCause() == null ? e : e.getCause());
        }
    }
}