aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/app/src/main/java/com/wireguard/config/InetNetwork.java
blob: 444af58ec168507ff3c6831318a5492d5fe69d97 (plain) (blame)
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
/*
 * Copyright © 2017-2018 WireGuard LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

package com.wireguard.config;

import java.net.Inet4Address;
import java.net.InetAddress;

/**
 * An Internet network, denoted by its address and netmask
 * <p>
 * Instances of this class are immutable.
 */
public final class InetNetwork {
    private final InetAddress address;
    private final int mask;

    private InetNetwork(final InetAddress address, final int mask) {
        this.address = address;
        this.mask = mask;
    }

    public static InetNetwork parse(final String network) throws ParseException {
        final int slash = network.lastIndexOf('/');
        final String maskString;
        final int rawMask;
        final String rawAddress;
        if (slash >= 0) {
            maskString = network.substring(slash + 1);
            try {
                rawMask = Integer.parseInt(maskString, 10);
            } catch (final NumberFormatException ignored) {
                throw new ParseException(Integer.class, maskString);
            }
            rawAddress = network.substring(0, slash);
        } else {
            maskString = "";
            rawMask = -1;
            rawAddress = network;
        }
        final InetAddress address = InetAddresses.parse(rawAddress);
        final int maxMask = (address instanceof Inet4Address) ? 32 : 128;
        if (rawMask > maxMask)
            throw new ParseException(InetNetwork.class, maskString, "Invalid network mask");
        final int mask = rawMask >= 0 && rawMask <= maxMask ? rawMask : maxMask;
        return new InetNetwork(address, mask);
    }

    @Override
    public boolean equals(final Object obj) {
        if (!(obj instanceof InetNetwork))
            return false;
        final InetNetwork other = (InetNetwork) obj;
        return address.equals(other.address) && mask == other.mask;
    }

    public InetAddress getAddress() {
        return address;
    }

    public int getMask() {
        return mask;
    }

    @Override
    public int hashCode() {
        return address.hashCode() ^ mask;
    }

    @Override
    public String toString() {
        return address.getHostAddress() + '/' + mask;
    }
}