How to get client IP and Server IP using Rails

前端 未结 2 725
广开言路
广开言路 2020-12-07 14:52

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

相关标签:
2条回答
  • 2020-12-07 15:13

    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

    0 讨论(0)
  • 2020-12-07 15:29

    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
    
    0 讨论(0)
提交回复
热议问题