微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Ruby中反转DNS?

我在一个环境中有很多电脑还没有
妥善盘点基本上没有人知道哪个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.gethostbyname,gethostbyaddr,但它不工作.

任何指导将不胜感激.

解决方法

我会查看getaddrinfo.如果换行:
host_name = Socket.gethostbyname(current_ip)

有:

host_name = Socket.getaddrinfo(current_ip,Socket::AF_UNSPEC,Socket::SOCK_STREAM,nil,Socket::AI_CANONNAME)[0][1]

getaddrinfo函数返回数组数组.您可以在以下位置阅读更多信息:

Ruby Socket Docs

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐