mirror of
https://github.com/Minestom/Minestom.git
synced 2025-01-03 23:17:48 +01:00
Move free port obtaining to util class
This commit is contained in:
parent
ec5ecb49bf
commit
f9245e8404
@ -3,6 +3,7 @@ package net.minestom.server.extras.lan;
|
|||||||
import net.minestom.server.MinecraftServer;
|
import net.minestom.server.MinecraftServer;
|
||||||
import net.minestom.server.event.server.ServerListPingEvent;
|
import net.minestom.server.event.server.ServerListPingEvent;
|
||||||
import net.minestom.server.timer.Task;
|
import net.minestom.server.timer.Task;
|
||||||
|
import net.minestom.server.utils.NetworkUtils;
|
||||||
import net.minestom.server.utils.time.Cooldown;
|
import net.minestom.server.utils.time.Cooldown;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@ -57,9 +58,7 @@ public class OpenToLAN {
|
|||||||
|
|
||||||
if (port == 0) {
|
if (port == 0) {
|
||||||
try {
|
try {
|
||||||
final ServerSocket socket = new ServerSocket(0);
|
port = NetworkUtils.getFreePort();
|
||||||
port = socket.getLocalPort();
|
|
||||||
socket.close();
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
LOGGER.warn("Could not find an open port!", e);
|
LOGGER.warn("Could not find an open port!", e);
|
||||||
return false;
|
return false;
|
||||||
|
29
src/main/java/net/minestom/server/utils/NetworkUtils.java
Normal file
29
src/main/java/net/minestom/server/utils/NetworkUtils.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user