Port Scanning with Java (#12767)

This commit is contained in:
ACHRAF TAITAI 2022-09-30 14:50:21 +02:00 committed by GitHub
parent 2d40c9c71d
commit e0272416f8
2 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,51 @@
package com.baeldung.portscanner;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class PortScanner {
private static final int poolSize = 10;
private static final int timeOut = 200;
public void runPortScan(String ip, int nbrPortMaxToScan) throws IOException, RuntimeException {
ConcurrentLinkedQueue openPorts = new ConcurrentLinkedQueue<>();
ExecutorService executorService = Executors.newFixedThreadPool(poolSize);
AtomicInteger port = new AtomicInteger(0);
while (port.get() < nbrPortMaxToScan) {
final int currentPort = port.getAndIncrement();
executorService.submit(() -> {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, currentPort), timeOut);
socket.close();
openPorts.add(currentPort);
System.out.println(ip + " ,port open: " + currentPort);
} catch (IOException e) {
System.err.println(e);
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
List openPortList = new ArrayList<>();
System.out.println("openPortsQueue: " + openPorts.size());
while (!openPorts.isEmpty()) {
openPortList.add(openPorts.poll());
}
openPortList.forEach(p -> System.out.println("port " + p + " is open"));
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.portScanner;
import com.baeldung.portscanner.PortScanner;
import org.junit.jupiter.api.Test;
import java.io.IOException;
class PortScannerUnitTest {
private static final int nbrPortMax = 1000; // Max is 65535, number of available ports
private static final String ip = "127.0.0.1";
PortScanner portScanner = new PortScanner();
@Test public void when_Run_then_lunchPortScan() throws IOException, RuntimeException {
portScanner.runPortScan(ip, nbrPortMax);
}
}