How to get my machine's IP address from Ruby without leveraging from other IP address?

后端 未结 5 474
说谎
说谎 2020-12-14 07:43

I have searched everywhere but their solution requires some form of IP address. Here are the solutions i have found.

    require \'socket\'
#METHOD 1
    ip          


        
相关标签:
5条回答
  • 2020-12-14 07:56

    parse the output of the ip command?

    from https://gist.github.com/henriquemenezes/a99f13da957515023e78aea30d6c0a48

    gw = `ip route show`[/default.*/][/\d+\.\d+\.\d+\.\d+/]
    

    or parse the output of the ipconfig command: https://stackoverflow.com/a/12632929/32453

    0 讨论(0)
  • 2020-12-14 08:00
    require 'socket'
    Socket::getaddrinfo(Socket.gethostname,"echo",Socket::AF_INET)[0][3]
    

    quite like method 1, actually

    0 讨论(0)
  • 2020-12-14 08:01

    This is what I've been using in production for years:

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

    Works great; tested on aws and classical hosting

    0 讨论(0)
  • 2020-12-14 08:05

    As there is no such thing as a default ip-interface to a host (there does not need to be any ip-interface at all actually) all assumptions regarding nameing are vague, do not necessarily hold.

    The value returned by gethostname() can be defined independently to any ip-setup, so it does not need to reflect a valid host in terms of a hostname which could be resolved to any ip-address.

    From the POSIX system's API's view the only reliabe function to test for the availablily of (ip-)interfaces is the function getifaddrs(), which returns a list of all interfaces along with their parameters.

    As it looks as if Ruby's current Socket lib does not provide an interface to it, this (http://rubygems.org/gems/system-getifaddrs) gem based approach does seem to be the only way to go.

    0 讨论(0)
  • 2020-12-14 08:15

    Isn't the solution you are looking for just:

    require 'socket'
    
    addr_infos = Socket.ip_address_list
    

    Since a machine can have multiple interfaces and multiple IP Addresses, this method returns an array of Addrinfo.

    You can fetch the exact IP addresses like this:

    addr_infos.each do |addr_info|
      puts addr_info.ip_address
    end
    

    You can further filter the list by rejecting loopback and private addresses, as they are usually not what you're interested in, like so:

    addr_infos.reject( &:ipv4_loopback? )
              .reject( &:ipv6_loopback? )
              .reject( &:ipv4_private? )
    
    0 讨论(0)
提交回复
热议问题