Move free port obtaining to util class

This commit is contained in:
Kieran Wallbanks 2021-04-25 22:41:13 +01:00
parent ec5ecb49bf
commit f9245e8404
2 changed files with 31 additions and 3 deletions

View File

@ -3,6 +3,7 @@ package net.minestom.server.extras.lan;
import net.minestom.server.MinecraftServer;
import net.minestom.server.event.server.ServerListPingEvent;
import net.minestom.server.timer.Task;
import net.minestom.server.utils.NetworkUtils;
import net.minestom.server.utils.time.Cooldown;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
@ -57,9 +58,7 @@ public class OpenToLAN {
if (port == 0) {
try {
final ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
port = NetworkUtils.getFreePort();
} catch (IOException e) {
LOGGER.warn("Could not find an open port!", e);
return false;

View File

@ -0,0 +1,29 @@
package net.minestom.server.utils;
import java.io.IOException;
import java.net.ServerSocket;
/**
* Network related utilities.
*/
public class NetworkUtils {
private NetworkUtils() { }
/**
* Gets a free port.
*
* @return the port
* @throws IOException if a port could not be found
*/
public static int getFreePort() throws IOException {
int port;
final ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
return port;
}
}