summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/config/IPCidr.java
blob: 245141ac5d5b7aea2b5bdf37f3c9269866799cd7 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.wireguard.config;

import android.os.Parcel;
import android.os.Parcelable;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPCidr implements Parcelable {
    InetAddress address;
    int cidr;


    public static final Parcelable.Creator<IPCidr> CREATOR = new Parcelable.Creator<IPCidr>() {
        @Override
        public IPCidr createFromParcel(final Parcel in) {
            return new IPCidr(in);
        }

        @Override
        public IPCidr[] newArray(final int size) {
            return new IPCidr[size];
        }
    };

    public IPCidr(String in) {
        parse(in);
    }

    private void parse(String in) {
        cidr = -1;
        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 (Exception e) {
            }
        }
        try {
            address = InetAddress.getByName(in);
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException(e);
        }
        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("%s/%d", address.getHostAddress(), cidr);
    }

    @Override
    public void writeToParcel(final Parcel dest, final int flags) {
        dest.writeString(this.toString());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    private IPCidr(final Parcel in) {
        try {
            parse(in.readString());
        } catch (Exception e) {
        }
    }

}