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 iterator() { return new PortRangeIterator(specifiedPorts); } }