summaryrefslogtreecommitdiff
path: root/src/main/java/com/it_jaros/jscanner/PortRange.java
blob: 8841162f45eb05bc70163ed50f6a55d732d9844e (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
77
78
package com.it_jaros.jscanner;

import java.util.BitSet;
import java.util.Iterator;

public class PortRange {

    public static final int MIN_PORT = 1;
    public static final int MAX_PORT = 65535;
    private final BitSet specifiedPorts = new BitSet(MAX_PORT);

    public PortRange(String ports) {
        if (ports == null || "".equals(ports)) {
            specifiedPorts.set(MIN_PORT, 1024);
        } else if ("all".equalsIgnoreCase(ports)) {
            specifiedPorts.set(MIN_PORT, MAX_PORT);
        } else {
            parsePortRange(ports);
        }
    }

    /**
     * Possible values are 1,10 or 1-10 or a mix of 1,5-10
     * So we treat , stronger and handle them first and then check for -
     *
     * @param ports
     */
    private void parsePortRange(String ports) {
        String[] splitComma = ports.split(",");
        for (String commaValue : splitComma) {
            String[] rangeValue = commaValue.split("-");

            // more then two values are not possible
            if (rangeValue.length > 2) {
                throw new IllegalArgumentException(String.format("Argument contains too many '-'' %s", commaValue));
            }

            // no range given, only single port
            int port = Integer.parseInt(rangeValue[0]);
            if (rangeValue.length == 1) {
                checkValue(port);
                specifiedPorts.set(port);
                continue;
            }

            // range given
            int end = Integer.parseInt(rangeValue[1]);
            checkValues(port, end);
            specifiedPorts.set(port, end + 1);
        }
    }

    private void checkValues(int start, int end) {
        checkValue(start);
        checkValue(end);

        if (start >= end) {
            throw new IllegalArgumentException(
                    String.format("Start value cannot be equal or bigger than end value '%s >= %s'", start, end));
        }
    }

    private void checkValue(int port) {
        if (port < MIN_PORT) {
            throw new IllegalArgumentException(
                    String.format("Port value is too low: %s < %s", port, MIN_PORT));
        }

        if (port > MAX_PORT) {
            throw new IllegalArgumentException(
                    String.format("Port value is too high: %s > %s", port, MAX_PORT));
        }
    }

    public Iterator<Integer> iterator() {
        return new PortRangeIterator(specifiedPorts);
    }
}