How to get the IP address of my local machine in Ruby?

前端 未结 3 953
广开言路
广开言路 2020-12-24 15:23

I am doing Rails development in Ubuntu 12.04LTS OS.

I want to capture my local IP address in a file, not the loopback 127.0.0.1, the one which I get using ifc

相关标签:
3条回答
  • 2020-12-24 16:10

    This is my first way:

    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
    
    # irb:0> local_ip
    # => "192.168.0.127"
    

    This is my second way, which is not recommended:

    require 'socket'
     Socket::getaddrinfo(Socket.gethostname,”echo”,Socket::AF_INET)[0][3]
    

    The third way:

     UDPSocket.open {|s| s.connect('64.233.187.99', 1); s.addr.last }
    

    And a fourth way:

    Use Socket#ip_address_list
    
    Socket.ip_address_list #=> Array of AddrInfo
    
    0 讨论(0)
  • 2020-12-24 16:13

    Use Socket::ip_address_list.

    Socket.ip_address_list #=> Array of AddrInfo
    
    0 讨论(0)
  • 2020-12-24 16:16

    Write below method

    def self.local_ip
        orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
        UDPSocket.open do |s|
          s.connect '64.233.187.99', 1
          s.addr.last
        end
        ensure
          Socket.do_not_reverse_lookup = orig
     end
    

    and then call local_ip method, you will get ip address of your machine.

    Eg: ip_address= local_ip
    
    0 讨论(0)
提交回复
热议问题