cx8tba
Last Updated: February 25, 2016
·
1.93K
· oesmith

Bind an EventMachine server to an ephemeral port

EventMachine will happily bind a server to an ephemeral port when you pass a port number of zero to EM.start_server.

sig = EM.start_server '127.0.0.1', 0, MyServer

However, if you'd like to know which port your server is now listening on, it's a little more complicated. There's no server object in EventMachine, so you can't just ask it for its port. That sig return value is actually a Fixnum that references a file descriptor.

This is the way to fetch the port number:

port = EM.Socket.unpack_sockaddr_in(
           EM.get_sockname(signature)).first

Obvious, huh?