Ruby中的反向DNS?

22

我处于一个很多电脑没有被彻底盘点的环境中。基本上,没有人知道哪个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,但都无法工作。

非常感谢您能提供任何指导。

3个回答

25

今天我也需要进行反向DNS查找,我发现了一个非常简单的标准解决方案:

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

似乎它使用了timeout来帮助处理一些复杂情况。


8
我建议您查看 getaddrinfo。如果您将以下行替换为:
host_name = Socket.gethostbyname(current_ip)

使用:

host_name = Socket.getaddrinfo(current_ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][1]
getaddrinfo函数返回一个数组的数组。您可以在以下链接中了解更多信息:

Ruby Socket文档


实际上这并不是在进行反向查找。你需要将第七个参数设置为 trueSocket.getaddrinfo(interesting_ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME, true) - akostadinov

2
这也可以运行:
host_name = Socket.getaddrinfo(current_ip,nil)
append_to_file("#{host_name[0][2]} - #{current_ip} - #{mac_addr}\n")

我不确定为什么gethostbyaddr也不起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接