Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client IP and Server IP using Rails

Can anyone please help how to get client IP and also server IP using Ruby on Rails?

like image 970
Senthil Kumar Bhaskaran Avatar asked Aug 04 '09 11:08

Senthil Kumar Bhaskaran


People also ask

How can we get the IP address of the client?

The answer is to use $_SERVER variable. For example, $_SERVER["REMOTE_ADDR"] would return the client's IP address.

How do I find my client IP address in laravel?

For getting the IP Address we have to include use Illuminate\Http\Request; in the controller and then add the code of the below pre tag. It will give the IP address of the network. $clientIP = \Request::ip(); dd($clientIP);


2 Answers

From your controller:

request.remote_ip 

If you are using apache in front of a mongrel, then remote_ip will return the source address of the request, which in this case will be local host because the Apache web server is making the request, so instead put this in your controller:

@remote_ip = request.env["HTTP_X_FORWARDED_FOR"] 

To get the server IP see:

Getting the Hostname or IP in Ruby on Rails

like image 90
karim79 Avatar answered Sep 17 '22 15:09

karim79


Thanks: karim79 and Titanous.

Write the code in Controller

For Client IP:

request.remote_ip  @remote_ip = request.env["HTTP_X_FORWARDED_FOR"] 

For Server IP:

require 'socket'  def local_ip   orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily    UDPSocket.open do |s|     s.connect '64.233.187.99', 1     s.addr.last   end ensure   Socket.do_not_reverse_lookup = orig end 
like image 20
Senthil Kumar Bhaskaran Avatar answered Sep 17 '22 15:09

Senthil Kumar Bhaskaran