如何在不利用其他IP地址的情况下从Ruby获取我的机器的IP地址? [英] How to get my machine's IP address from Ruby without leveraging from other IP address?

查看:141
本文介绍了如何在不利用其他IP地址的情况下从Ruby获取我的机器的IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处搜索,但他们的解决方案需要某种形式的IP地址。
以下是我找到的解决方案。

  require'socket'
#METHOD 1
ip = IPSocket.getaddress(Socket.gethostname)
put ip

#METHOD 2
host = Socket.gethostname
put host

#METHOD 3(使用Google的地址)
ip = UDPSocket.open {| s | s.connect(64.233.187.99,1); s.addr.last}
put ip

#METHOD 4(使用网关地址)
def local_ip
orig,Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup,true#暂时关闭反向DNS解析

UDPSocket.open do | s |
s.connect'192.168.1.1',1
s.addr.last
end
确保
Socket.do_not_reverse_lookup = orig
end

ip = local_ip
put ip

所有这些都需要IP地址有人。有没有使用别人的IP地址的解决方案?优选地,平台无关。

解决方案

不是您正在寻找的解决方案:

  require'socket'

addr_infos = Socket.ip_address_list

由于一台机器可以有多个接口和多个IP地址,因此该方法返回一个 Addrinfo



您可以像这样获取确切的IP地址:

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

P.S。问题有点陈旧,但显示为Google上的第一项,并且它不包含大多数人正在寻找的解决方案,所以我决定发布它。



<希望它有所帮助。


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.

解决方案

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

P.S. The question is a bit old, but shows up as the first item on Google and it doesn't contain the solution most people are looking for, so I decided to post it.

Hope it helps.

这篇关于如何在不利用其他IP地址的情况下从Ruby获取我的机器的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆