[英]Get own IP address
How to get my own IP address with Rails?如何使用 Rails 获取我自己的 IP 地址?
When I do it like this I got: 127.0.0.1
当我这样做时,我得到了:
127.0.0.1
@ip = request.remote_ip
Is there any way to get the Public IP?有没有办法获得公共IP?
Try:尝试:
require 'socket'
ip=Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
ip.ip_address if ip
我相信request.env['SERVER_NAME']
工作,如果你想反映服务器基地址
试试这个:
request.env['REMOTE_ADDR']
Call the page using your IP, not localhost.使用您的 IP 调用页面,而不是本地主机。 Ie,
192.168.2.9:3000
in case of the default development environment would yield:即,
192.168.2.9:3000
在默认开发环境的情况下会产生:
request.env['REMOTE_ADDR']
#=> 192.168.2.9
or:要么:
request.remote_ip
#=> 192.168.2.9
As your request is local to the server, it returns the "localhost" address, ie 127.0.0.1
.由于您的请求是服务器本地的,因此它返回“localhost”地址,即
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.如果您从托管在 Internet 上的机器请求它,它将为您提供远程服务器的静态 IP。
If you want the static IP of own internet then visit http://ping.eu and you can see your public IP.如果您想要自己互联网的静态 IP,请访问http://ping.eu ,您可以看到您的公共 IP。
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.所以,当我在真实的移动设备上
debug
/ hot reload
/ live reload
应用程序时。 Images url does not work with localhost:3000
.图像 url 不适用于
localhost:3000
。
Images works with ip like this: http://192.168.0.102:3000/user/1/profile-223hfkj33.jpg
图像与这样的 ip 一起使用:
http://192.168.0.102:3000/user/1/profile-223hfkj33.jpg
: http://192.168.0.102:3000/user/1/profile-223hfkj33.jpg
: 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. Problem is
每次我打开笔记本电脑并连接到wifi路由器时,笔记本电脑的ip都会发生变化。 So, every-time I need to change asset_host
in environments/development.rb
file.所以,每次我需要在
environments/development.rb
文件中更改asset_host
时。
Looking at previous answers I found a solution:查看以前的答案,我找到了一个解决方案:
Solution:解决方案:
in environments/development.rb
I write this code:在
environments/development.rb
我写了这段代码:
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
所以,它设置
asset_host
像这样: 192.168.0.102:3000
: asset_host
And when I turn on laptop, laptop gets new ip address and it works.当我打开笔记本电脑时,笔记本电脑会获得新的 IP 地址并且可以正常工作。
Socket.ip_address_list.detect(&:ipv4_private?).ip_address
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.