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; } }