Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

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

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 = IPSocket.getaddress(Socket.gethostname)
    puts ip 

#METHOD 2
    host = Socket.gethostname
    puts host

#METHOD 3(uses Google's address)
    ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}
    puts ip

#METHOD 4(uses gateway address)
    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 '192.168.1.1', 1
        s.addr.last
      end
    ensure
      Socket.do_not_reverse_lookup = orig
    end

    ip=local_ip
    puts ip

All of them require IP address of someone. Is there a solution that does not use someone else's IP address? Preferably, platform independent.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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? )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...