Skip to content

Instantly share code, notes, and snippets.

@fsvehla
Created September 8, 2022 09:50
Show Gist options
  • Save fsvehla/0f9b584494557cb1731d9e5c73229323 to your computer and use it in GitHub Desktop.
Save fsvehla/0f9b584494557cb1731d9e5c73229323 to your computer and use it in GitHub Desktop.
// 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