Forum: Ruby on Rails how do I get the host or Ip address where my rails app is running

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kad K. (Guest)
on 2008-12-11 19:04
(Received via mailing list)
Hi

I would like to get in a variable the ip address of the host where my
app is running, to change some parameters if it's running locally or
remotely .. is it possible ?

I cannot use request.host, since there is no request yet

I suppose I should test it in application.rb, not in environment.rb
during initialization ..

thanks for your suggestions ..

erwin
Mark Reginald J. (Guest)
on 2008-12-12 01:22
(Received via mailing list)
Erwin wrote:

> I would like to get in a variable the ip address of the host where my
> app is running, to change some parameters if it's running locally or
> remotely .. is it possible ?

You can try

require 'socket'
REAL_PRODUCTION = Socket.gethostname == 'mysite.com'

or

hostinfo = Socket.gethostbyname(Socket.gethostname)
hostnames = hostinfo[1] << hostinfo[0]
REAL_PRODUCTION = hostnames.include?('mysite.com')

--
Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com
Qas W. (Guest)
on 2010-01-08 18:16
Mark Reginald J. wrote:
> You can try
>
> require 'socket'
> REAL_PRODUCTION = Socket.gethostname == 'mysite.com'
>
> or
>
> hostinfo = Socket.gethostbyname(Socket.gethostname)
> hostnames = hostinfo[1] << hostinfo[0]
> REAL_PRODUCTION = hostnames.include?('mysite.com')
>
> --
> Rails Wheels - Find Plugins, List & Sell Plugins -
> http://railswheels.com

This returns the hostname from the box where the site is running which
can help as well but is there a way to get the ip of the box?

I have tried to mirror two different servers this way i can test on one
and deploy on the other and also keep the other as a backup should i
ever need to redeploy to the other so the hostname and all are the same.
(this maybe wrong way to do things so you may correct me)...

So my issue comes that the hostname is same on both machines and only
the ip will do.
Sijo k. (Guest)
on 2010-01-08 20:21
Hi Kad K.

require 'ipaddr'
require 'net/http'

def get_ip
 con = Net::HTTP.new('checkip.dyndns.org', 80)
 resp,body = con.get("/", nil)
 ip = body.match(/\d+\.\d+\.\d+\.\d+/)

 ip[0]
end

my_ip = IPAddr.new(get_ip)



Sijo
Qas W. (Guest)
on 2010-01-08 20:43
Thanks Sijo. This will help a lot.

Sijo k g wrote:
> Hi Kad K.
> require 'ipaddr'
> require 'net/http'
> def get_ip
>  con = Net::HTTP.new('checkip.dyndns.org', 80)
>  resp,body = con.get("/", nil)
>  ip = body.match(/\d+\.\d+\.\d+\.\d+/)
>
>  ip[0]
> end
> my_ip = IPAddr.new(get_ip)
This topic is locked and can not be replied to.