summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/config/IPCidr.java
blob: bfa92e0711323a11cc966889892c4756c59a048d (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
/*
 * Copyright © 2018 Samuel Holland <samuel@sholland.org>
 * Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

package com.wireguard.config;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.Locale;

public class IPCidr {
    private final InetAddress address;
    private int cidr;

    @SuppressWarnings("MagicNumber")
    public IPCidr(String in) {
        cidr = -1;
        final int slash = in.lastIndexOf('/');
        if (slash != -1 && slash < in.length() - 1) {
            try {
                cidr = Integer.parseInt(in.substring(slash + 1), 10);
                in = in.substring(0, slash);
            } catch (final Exception ignored) {
            }
        }
        address = Attribute.parseIPString(in);
        if ((address instanceof Inet6Address) && (cidr > 128 || cidr < 0))
            cidr = 128;
        else if ((address instanceof Inet4Address) && (cidr > 32 || cidr < 0))
            cidr = 32;
    }

    public InetAddress getAddress() {
        return address;
    }

    public int getCidr() {
        return cidr;
    }

    @Override
    public String toString() {
        return String.format(Locale.getDefault(), "%s/%d", address.getHostAddress(), cidr);
    }
}