blob: 1f71f566e7bda61d034e9f3b430b12076c1b3817 (
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
|
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<Integer> scanPorts(String address) {
return scanPorts(address, socketLimitDefault);
}
public List<Integer> scanPorts(String address, int socketLimit) {
Queue<Integer> 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();
}
}
|