package com.it_jaros.networkScanner; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class Scanner { private Counter counter = new Counter(); private final int socketLimitDefault = 1024; public Scanner() {} public List scanPorts(ScanTarget target) { return scanPorts(target.address(), target.openSocketLimit()); } public List scanPorts(String address) { return scanPorts(address, socketLimitDefault); } public List scanPorts(String address, int socketLimit) { Queue openPorts = new ConcurrentLinkedQueue<>(); Semaphore socketCap = new Semaphore(socketLimit); try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int port = 1; port < 65536; port++) { final int currentPort = port; executor.submit(() -> { socketCap.acquireUninterruptibly(); counter.inc(); try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(address, currentPort)); openPorts.add(currentPort); } catch (ConnectException ignored) { } catch (IOException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); } finally { counter.dec(); socketCap.release(); } }); } } System.out.println("Peak concurrent connects: " + counter.max()); return openPorts.stream().toList(); } }