Searching for available port method

This commit is contained in:
Mei Chang van der Werff 2026-01-16 03:30:11 +01:00
commit bc144b52ae

View file

@ -0,0 +1,39 @@
package server;
import java.io.IOException;
import java.net.ServerSocket;
public class PortChecker {
private int defaultPort = 8080;
private int lastPort = 8090; // To limit the amount of ports to look for availability
/**
* Finds a free port to launch the program on
* made with the help of https://medium.com/@rrlinus5/find-available-port-in-your-system-java-f532ee48c5b3
* @return the port that will be used to launch the program
* @throws IOException when no available port is found
*/
public int findFreePort() throws IOException {
for (int port = defaultPort; port <= lastPort; port++) {
if(isPortAvailable(port)){
return port;
}
}
throw new IOException("No free port found");
}
/**
* Checks whether a port is actually available
* @param port the number of the port that's being checker
* @return whether the port was available
*/
public boolean isPortAvailable(int port){
try(ServerSocket socket = new ServerSocket(port)){
return true;
}catch(IOException i) {
return false;
}
}
}