summaryrefslogtreecommitdiff
path: root/src/main/java/com/it_jaros/networkScanner/PortRange.java
blob: 6f1c5290e2aedad781aca397b72f570c850f43d1 (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
package com.it_jaros.networkScanner;

import java.util.BitSet;
import java.util.NoSuchElementException;

public class PortRange {

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

    private int cursor;
    private int done = 0;

    public PortRange(String ports) {
        if (ports == null || "".equals(ports)) {
            // keep defaults
            specifiedPorts.set(1, 1024 + 1);
            return;
        }

        String[] splitComma = ports.split(",");
        for (String commaValue: splitComma) {
            if (commaValue.contains("-")) {
                String[] rangeValue = commaValue.split("-");
                if (rangeValue.length > 2) {
                    throw new IllegalArgumentException(String.format("Argument contains too many '-'' %s", commaValue));
                }
                
                int start = Integer.parseInt(rangeValue[0]);
                int end = Integer.parseInt(rangeValue[1]);
                specifiedPorts.set(start, end + 1);
            } else {
                specifiedPorts.set(Integer.parseInt(commaValue));
            }
        }
        
        availablePorts.or(specifiedPorts);
        cursor = availablePorts.nextSetBit(MIN_PORT);
    }

    public synchronized int next() {
        int p = availablePorts.nextSetBit(cursor);
        if (p > 0) {
            availablePorts.clear(p);
            cursor = p + 1;
            done++;
            return p;
        }

        throw new NoSuchElementException("Reached end of port range");
    }

    public synchronized boolean hasNext() {
        return availablePorts.nextSetBit(cursor) > 0;
    }

    public int getTotal() {
        return specifiedPorts.cardinality();
    }

    public int getDone() {
        return done;
    }
}