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
84
85
86
87
88
89
90
91
|
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]);
checkValues(start, end);
specifiedPorts.set(start, end + 1);
} else {
int port = Integer.parseInt(commaValue);
checkValue(port);
specifiedPorts.set(Integer.parseInt(commaValue));
}
}
availablePorts.or(specifiedPorts);
cursor = availablePorts.nextSetBit(MIN_PORT);
}
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("Start value smaller than allowed range %s < %s", port, MIN_PORT));
}
if (port > MAX_PORT) {
throw new IllegalArgumentException(
String.format("End value bigger than allowed range %s > %s", port, MAX_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;
}
}
|