mirror of
https://github.com/Melledy/LunarCore.git
synced 2025-12-16 07:14:58 +01:00
(feat.) Check if the MongoDB port is open before binding to it
This commit is contained in:
@@ -2,6 +2,7 @@ package emu.lunarcore.database;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import emu.lunarcore.util.Utils;
|
||||
import org.bson.codecs.configuration.CodecRegistries;
|
||||
import org.reflections.Reflections;
|
||||
|
||||
@@ -41,11 +42,12 @@ public final class DatabaseManager {
|
||||
|
||||
public DatabaseManager(DatabaseInfo info, ServerType type) {
|
||||
// Variables
|
||||
var internalConfig = LunarCore.getConfig().getInternalMongoServer();
|
||||
String connectionString = info.getUri();
|
||||
|
||||
// Local mongo server
|
||||
if (info.isUseInternal()) {
|
||||
connectionString = startInternalMongoServer(LunarCore.getConfig().getInternalMongoServer());
|
||||
if (info.isUseInternal() && Utils.isPortOpen(internalConfig.getAddress(), internalConfig.getPort())) {
|
||||
connectionString = startInternalMongoServer(internalConfig);
|
||||
LunarCore.getLogger().info("Using local mongo server at " + server.getConnectionString());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package emu.lunarcore.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
@@ -157,4 +161,21 @@ public class Utils {
|
||||
public static byte[] base64Decode(String toDecode) {
|
||||
return Base64.getDecoder().decode(toDecode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a port is open on a given host.
|
||||
*
|
||||
* @param host The host to check.
|
||||
* @param port The port to check.
|
||||
* @return True if the port is open, false otherwise.
|
||||
*/
|
||||
public static boolean isPortOpen(String host, int port) {
|
||||
try (var serverSocket = new ServerSocket()) {
|
||||
serverSocket.setReuseAddress(false);
|
||||
serverSocket.bind(new InetSocketAddress(InetAddress.getByName(host), port), 1);
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user