diff --git a/server/src/main/java/server/PortChecker.java b/server/src/main/java/server/PortChecker.java new file mode 100644 index 0000000..5a0a29a --- /dev/null +++ b/server/src/main/java/server/PortChecker.java @@ -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; + } + } +} + +