How do I get the host or Ip address where my rails app is running


#1

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


#2

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


#3

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.


#4

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


#5

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)