Get own IP address - ruby-on-rails

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?

Try:
require 'socket'
ip=Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
ip.ip_address if ip

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

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

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.

Try this:
request.env['REMOTE_ADDR']

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.

Related

Docker - URL syntax [duplicate]

What is the format for the PostgreSQL connection string (URL postgres://...) when the host is not the localhost?
If you use Libpq binding for respective language, according to its documentation URI is formed as follows:
postgresql://[user[:password]#][netloc][:port][/dbname][?param1=value1&...]
Here are examples from same document
postgresql://
postgresql://localhost
postgresql://localhost:5432
postgresql://localhost/mydb
postgresql://user#localhost
postgresql://user:secret#localhost
postgresql://other#localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://localhost/mydb?user=other&password=secret
The following worked for me
const conString = "postgres://YourUserName:YourPassword#YourHostname:5432/YourDatabaseName";
DATABASE_URL=postgres://{user}:{password}#{hostname}:{port}/{database-name}
Here is the documentation for JDBC, the general URL is "jdbc:postgresql://host:port/database"
Chapter 3 here documents the ADO.NET connection string,
the general connection string is Server=host;Port=5432;User Id=username;Password=secret;Database=databasename;
PHP documentation us here, the general connection string is
host=hostname port=5432 dbname=databasename user=username password=secret
If you're using something else, you'll have to tell us.
the connection url for postgres
syntax:
"Server=host ipaddress;Port=5432;Database=dbname;User Id=userid;Password=password;
example:
"Server=192.168.1.163;Port=5432;Database=postgres;User Id=postgres;Password=root;
server.address=10.20.20.10
server.port=8080
database.user=username
database.password=password
spring.datasource.url=jdbc:postgresql://${server.address}/${server.port}?user=${database.user}&password=${database.password}
The connection string can also be retrieved programmatically from working DB connectors.
For instance I sometimes extract connection strings from SQLAlchemy's engine, like this:
> db_engine.url
postgres://{user}:{password}#{host}:{port}/{db_name}?sslmode=require
Some people seem to misread the database name as a server name and the host as a postgresql server? A host hosts a postgresql server that has a database. Or am I missing something.
postgresql://my_host/&server=my_postgresql_server?user=my_user&port=my_port&password=my_password&database=my_database
Example:
my_host: can be "localhost" (but that is not in the question) or an ip address of a host.
postgresql://my_host/&server=postgres?user=postgres&port=5432&password=postgres&database=test_db
Worked for me in Python with sqlalchemy and a postgresql localhost running. Needs sqlalchemy, postgresql, and psycopg2 to get it to work.
PS: The question is about a postgres://... URL, but this would not work here. Instead, you need postgresql, and what is run in the end in Python is dialect+driver (see Database URLs) = postgresql+psycopg2, without having to write it like this.
The general format of database url
DATABASE_URL=postgresql://username:password#host:port/dtabase_name
If you are using postgresql sql with asyncpg the database url would be
DATABASE_URL=postgresql+asyncpg://username:password#host:port/dtabase_name
Remember to never push your database password so you should use your DATABASE_URL in .env file
The port is optional if you use the default one
Like this you can connect both local and remote database think of that once you want to check an issue that occur in the remote deployed versions
ex of localhost DATABASE_URL would be
DATABASE_URL=postgresql+asyncpg://postgres:dina#localhost/mysens
If you deployed your database on Heroku and you want to connect it with your local app, go to Heroku Postgres installed add-on go to settings and click on view credential in Database Credentials and use the uri to connect to your database
DATABASE_URL=postgresql+asyncpg://sqnalxxxxxxxxx:160xxxx2bdd2942b26c93c392xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx#ec2-35-173-91-114.compute-1.amazonaws.com:5432/del6o4cjoqfsov

Capturing IP address from a form

I have a rails form and am trying to capture a client's IP address and ultimately convert that into a zip code. I've done the following:
Controller
def create
...
begin
response = open('https://jsonip.com/').read
data = JSON.parse(response)
ip_address = data['ip']
ip_type = 'jsonip'
rescue
ip_type = 'request.remote_ip'
ip_address = request.remote_ip
end
if ip_address
zip = Geocoder.search(ip_address)
p "IP Address (#{ip_type}): #{ip_address}, zip: #{zip}"
#potential_client.zip_code = zip.first.try(:postal) if zip.present?
end
...
end
This code came from here because request.remote_ip kept returning the same IP address. It seemed to work but once I push to Heroku, it seems like everyone is still coming from the same IP address.
What else am I missing?
With the call to jsonip.com, that is your server rendering and requesting that page so it makes sense that the server IP is returned.
With Heroku and other SaaS providers the remote IP will return the IP of the server or load balancer. Heroku does provide a header "x-forwarded-for" that has a list of IPs the request has passed through.

Getting IP Address current server

I used symfony 1.4 to create my application.
I'd like to get the IP adress of the current server to put it within soap request
So, how can i get the IP address of the current server?
For most situations, using $_SERVER['SERVER_ADDR']; will work. If that doesn't work you can try $ip = gethostbyname(gethostname());
If you have access to the $request object and it is a sfWebRequest (typical request from a browser) you can use:
$request->getPathInfoArray()['SERVER_ADDR']
Premise of the following method: your domain name has only one IP resolution
Using PHP:
gethostbyname($_SERVER['SERVER_NAME'])
$_SERVER['SERVER_NAME']will generally return your domain name (server_name / ServerName is configured in Nginx / Apache server), and then use gethostbyname().
About $_SERVER['SERVER_ADDR'], it often return a LAN IP address (I only have one server, one domain name, no reverse proxy; cloud server).
About gethostname()
In the test, it returns the name of the server (host name, not the domain name you use), and then uses gethostbyname(), will return a LAN IP.
More can be used https://checkip.amazonaws.com/ Get the current IP.

Advice on how to set up a connection between nancy service and server

I am working on a project whereby we have sites (developed with ruby on rails) hosted on an Ubuntu server using tomcat. We want these sites to make HTTP calls to a service developed using Nancy. We have this working locally whereby the service is hosted on a machine that we can call within our network. We cannot however get it working when live. Here is an example call:
def get_call(routePath)
started_at = Time.now
enc_url = URI.encode("#{settings.service_endpoint}#{routePath}")
uri = URI.parse(enc_url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.request_uri)
resp = http.request(req)
logger.bench 'SERVICE - GET', started_at, routePath
return resp if response_ok?(resp)
end
When working locally the settings are as follows:
settings.service_endpoint = http://10.10.10.27:7820
routePath = /Customers
When we upload it to the server we use the following:
settings.service_endpoint = http://127.0.0.1:24099
routePath = /Customers
We currently get the following error:
SocketError at /register
initialize: name or service not know
with the following line being highlighted:
resp = http.request(req)
Are we completely wrong with the IP being called. Should it be 127.0.0.1, localhost. 10.10.10.27 or something entirely different? The strange thing is we can do a GET call via telnet in our Ubuntu server (telnet 127.0.0.1 24099) so that must mean the server can make the calls but the site hosted on the server cannot. Do we need to include a HTTP proxy (have read some reference to that but dont really know if its needed).
Apologies if its obvious but we have never tried anything like this before so its all very perplexing. Any further information required just let me know.
We changed the service_endpoint to localhost and it worked. Not sure if this is because it didnt like "http://" or some other reason. Any explanation as to why this is the case would be much appreciated, just so we know. Thanks!

How to use $remote_addr with rails and nginx secure_link

I have a rails application that makes calls to another server via net::http to retrieve documents.
I have set up Nginx with secure_link.
The nginx config has
secure_link $arg_md5,$arg_expires;
secure_link_md5 "$secure_link_expires$uri$remote_addr mySecretCode";
On the client side (which is in fact my rails server) I have to create the secure url something like:
time = (Time.now + 5.minute).to_i
hmac = Digest::MD5.base64digest("#{time}/#{file_path}#{IP_ADDRESS} mySecretCode").tr("+/","-_").gsub("==",'')
return "#{DOCUMENT_BASE_URL}/#{file_path}?md5=#{hmac}&expires=#{time}"
What I want to know is the best way to get the value above for IP_ADDRESS
There are multiple answers in SO on how to get the ip address but alot of them do not seem as reliable as actually making a request to a web service that returns the ip address of the request as this is what the nginx secure link will see (we don't want some sort of localhost address).
I put the following method on my staging server:
def get_client_ip
data=Hash.new
begin
data[:ip_address]=request.ip
data[:error]=nil
rescue Exception =>ex
data[:error]=ex.message
end
render :json=>data
end
I then called the method from the requesting server:
response = Net::HTTP.get_response(URI("myserver.com/web_service/get_client_ip"))
if response.class==Net::HTTPOK
response_hash=JSON.parse response.body
ip=response_hash["ip_address"] unless response_hash[:error]
else
#deal with error
end
After getting the ip address successfully I just cached it and did not keep on calling the web service method.

Resources