ruby - 在 Ruby 中反向 DNS?

标签 ruby sockets dns nslookup

我处在一个有很多计算机的环境中 适当盘点。基本上,没有人知道哪个IP对应哪个 mac地址和哪个主机名。所以我写了以下内容:

# This script goes down the entire IP range and attempts to
# retrieve the Hostname and mac address and outputs them
# into a file. Yay!

require "socket"

TwoOctets = "10.26"

def computer_exists?(computerip)
 system("ping -c 1 -W 1 #{computerip}")
end

def append_to_file(line)
 file   = File.open("output.txt", "a")
 file.puts(line)
 file.close
end


def getInfo(current_ip)
 begin
   if computer_exists?(current_ip)
     arp_output = `arp -v #{current_ip}`
     mac_addr = arp_output.to_s.match(/..:..:..:..:..:../)
     host_name = Socket.gethostbyname(current_ip)
     append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n")
   end
 rescue SocketError => mySocketError
   append_to_file("unknown - #{current_ip} - #{mac_addr}")
 end
end


(6..8).each do |i|
 case i
   when 6
     for j in (1..190)
       current_ip = "#{TwoOctets}.#{i}.#{j}"
       getInfo(current_ip)
     end
   when 7
     for j in (1..255)
       current_ip = "#{TwoOctets}.#{i}.#{j}"
       getInfo(current_ip)
     end
   when 8
     for j in (1..52)
       current_ip = "#{TwoOctets}.#{i}.#{j}"
       getInfo(current_ip)
     end
 end
end

除了找不到反向 DNS 之外一切正常。

我得到的示例输出是这样的:

10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F
10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3
10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2

如果我执行 nslookup 10.26.6.12 然后我得到正确的反向 DNS 所以 这表明我的机器正在访问 DNS 服务器。

我试过Socket.gethostbynamegethostbyaddr,但都不行。

任何指导将不胜感激。

最佳答案

今天我还需要反向 DNS 查找,我找到了非常简单的标准解决方案:

require 'resolv'
host_name = Resolv.getname(ip_address_here)

它似乎使用了超时,这在一些棘手的情况下会有所帮助。

关于ruby - 在 Ruby 中反向 DNS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2993/

相关文章:

ruby-on-rails - 从 jail 长或设计中获取 session ID

ruby-on-rails - OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed - rake 任务到外部 API

ruby - 在 ruby​​ 中,我怎么知道哪个模块被定义为 'load' 或 'require' 的结果?

ruby-on-rails - 如何在邮寄方法的邮寄布局中包含条件?

java - tcp socket 的 read 方法如何工作?

c++ - 如何在 C++ 中创建 OpenVPN 客户端? (不是一个 tun/tap 经理,一个真正的客户)

sockets - ZeroMQ:我们可以 .bind() 100+ 个套接字到同一个端点吗?

ruby-on-rails - 用于 Mac OS 上开发的本地域名

copy - 如何使用 robocopy 复制不同域上的目录

c# - 如何获取指定主机名的DNS别名?