...
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package util
|
||||
import java.net.ServerSocket
|
||||
|
||||
object PortFinder {
|
||||
/**
|
||||
* 사용 가능한 두 개의 포트를 찾아 Pair(첫번째, 두번째)로 반환합니다.
|
||||
* @param startPort 검색을 시작할 포트 번호
|
||||
* @param mustBeConsecutive true일 경우 두 포트가 연속번호(ex: 18080, 18081)여야 함
|
||||
*/
|
||||
fun findAvailablePortPair(startPort: Int, mustBeConsecutive: Boolean = true): Pair<Int, Int> {
|
||||
var currentPort = startPort
|
||||
|
||||
while (currentPort < 65534) {
|
||||
if (isPortAvailable(currentPort)) {
|
||||
if (mustBeConsecutive) {
|
||||
// 연속된 포트가 필요한 경우 (n, n+1)
|
||||
if (isPortAvailable(currentPort + 1)) {
|
||||
return Pair(currentPort, currentPort + 1)
|
||||
}
|
||||
} else {
|
||||
// 연속될 필요 없는 경우, 그다음 사용 가능한 포트를 찾음
|
||||
val secondPort = findAvailablePort(currentPort + 1)
|
||||
return Pair(currentPort, secondPort)
|
||||
}
|
||||
}
|
||||
currentPort++
|
||||
}
|
||||
throw RuntimeException("⚠️ 사용 가능한 포트 쌍을 찾을 수 없습니다.")
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 포트 가용성 체크 (기존 로직 유지)
|
||||
*/
|
||||
fun findAvailablePort(startPort: Int): Int {
|
||||
for (port in startPort..65535) {
|
||||
if (isPortAvailable(port)) return port
|
||||
}
|
||||
throw RuntimeException("⚠️ 사용 가능한 포트가 없습니다.")
|
||||
}
|
||||
|
||||
private fun isPortAvailable(port: Int): Boolean {
|
||||
return try {
|
||||
ServerSocket(port).use { socket ->
|
||||
socket.reuseAddress = true
|
||||
true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user