To put it otherwise, is there another way to start a server on a available port than trying to connect it on a given port, increment the port number and so on by trial and error?
I think that’s what happens when you connect to port zero.
Yes. That’s exactly what HTTP::Server.bind_unused_port
does.
# Creates a `TCPServer` listening on an unused port and adds it as a socket.
#
# Returns the `Socket::IPAddress` with the determined port number.
#
# ```
# require "http/server"
#
# server = HTTP::Server.new { }
# server.bind_unused_port # => Socket::IPAddress.new("127.0.0.1", 12345)
# ```
def bind_unused_port(host : String = Socket::IPAddress::LOOPBACK, reuse_port : Bool = false) : Socket::IPAddress
bind_tcp host, 0, reuse_port
end
# Creates a `UNIXServer` bound to *path* and adds it as a socket.
#
# ```
# require "http/server"
#
# server = HTTP::Server.new { }
# server.bind_unix "/tmp/my-socket.sock"
2 Likes