How to find the local port a rails instance is running on?

Viewed 15868

So I would like my Rails app instances to register themselves on a "I'm up" kind of thing I'm playing with, and I'd like it to be able to mention what local port it's running on. I can't seem to find how to do it - in fact just finding out its IP is tricky and needs a bit of a hack.

But no problem, I have the IP - but how can I find what port my mongrel/thin/webrick server is running on?

To be super explicit, if I start a rails app using script/server -p 3001, what can I do to pull that 3001 inside the app.

6 Answers

Building on the other answers (which saved my bacon!), I expanded this to give sane fallbacks:

In development:

port = Rails::Server::Options.new.parse!(ARGV)[:Port] || 3000 rescue 3000

In all other env's:

port = Rails::Server::Options.new.parse!(ARGV)[:Port] || 80 rescue 80

The rescue 80 covers you if you're running rails console. Otherwise, it raises NameError: uninitialized constant Rails::Server. (Maybe also early in initializers? I forget...)

The || 80 covers you if no -p option is given to server. Otherwise you get nil.

Related