Searching for available port method
This commit is contained in:
parent
624a0cbe86
commit
bc144b52ae
1 changed files with 39 additions and 0 deletions
39
server/src/main/java/server/PortChecker.java
Normal file
39
server/src/main/java/server/PortChecker.java
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue