18

How to get my own IP address with Rails?

When I do it like this I got: 127.0.0.1

@ip = request.remote_ip

Is there any way to get the Public IP?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
amtest
  • 690
  • 1
  • 6
  • 26

6 Answers6

45

Try:

require 'socket'
ip=Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
ip.ip_address if ip
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Salil
  • 46,566
  • 21
  • 122
  • 156
1

I believe request.env['SERVER_NAME'] works, if you want to reflect the server base address back

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
JonB
  • 11
  • 1
1

This does not answer this question. I think someone else can find this answer helpful.

Problem:

I am developing a mobile app. So, When I debug/hot reload/live reload the app in real mobile device. Images url does not work with localhost:3000.

Images works with ip like this: http://192.168.0.102:3000/user/1/profile-223hfkj33.jpg

Problem is Every time I turn on laptop and connect to wifi router, laptop ip changes. So, every-time I need to change asset_host in environments/development.rb file.

Looking at previous answers I found a solution:

Solution:

in environments/development.rb I write this code:

server_address = "#{Socket.ip_address_list.detect(&:ipv4_private?).try(:ip_address)}:3000"
config.asset_host = server_address

puts "Server address: #{server_address}"
# when I run `rails s`, this line prints server address in console

So, It sets asset_host like this: 192.168.0.102:3000
And when I turn on laptop, laptop gets new ip address and it works.

mahfuz
  • 2,728
  • 20
  • 18
0

Try this:

request.env['REMOTE_ADDR']
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
PradeepKumar
  • 1,259
  • 9
  • 5
0

Call the page using your IP, not localhost. I.e, 192.168.2.9:3000 in case of the default development environment would yield:

request.env['REMOTE_ADDR']
#=> 192.168.2.9

or:

request.remote_ip 
#=> 192.168.2.9 
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Pritesh Jain
  • 9,106
  • 4
  • 37
  • 51
0

As your request is local to the server, it returns the "localhost" address, i.e. 127.0.0.1. If you request it from a machine hosted on the internet, it will give you a static IP of the remote server.

If you want the static IP of own internet then visit http://ping.eu and you can see your public IP.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sandip Ransing
  • 7,583
  • 4
  • 37
  • 48