Created
September 8, 2022 09:50
-
-
Save fsvehla/0f9b584494557cb1731d9e5c73229323 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// intersection of macOS, Linux and Windows ephemeral ports | |
val EphemeralPortRange: Range.Inclusive = | |
49152 to 60999 | |
val freePort: IO[IOException, Int] = { | |
def ensureAvailable(int: Int): IO[IOException, Unit] = | |
ZIO.attemptBlockingIO { | |
ServerSocketFactory | |
.getDefault | |
.createServerSocket(int, 1 /* backlog */ , InetAddress.getByName("localhost")) | |
.close() | |
} | |
val available = for { | |
port <- Random.nextIntBetween(EphemeralPortRange.start, EphemeralPortRange.end) | |
_ <- ensureAvailable(port) | |
} yield port | |
available.retry(Schedule.spaced(10.millis).upTo(1.second)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment