【问题标题】:Reverse DNS in Ruby?Ruby中的反向DNS?
【发布时间】:2010-09-05 09:41:12
【问题描述】:

我所处的环境有很多尚未使用过的计算机 适当地盘点。基本上,没有人知道哪个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,但都不管用。

任何指导将不胜感激。

【问题讨论】:

    标签: ruby sockets dns nslookup


    【解决方案1】:

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

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

    它似乎使用了超时,这在粗略的情况下会有所帮助。

    【讨论】:

      【解决方案2】:

      我会查看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 Docs

      【讨论】:

      • 其实这并不是在做反向查找。你需要使第7个参数true:Socket.getaddrinfo(interesting_ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME, true)
      【解决方案3】:

      这也有效:

      host_name = Socket.getaddrinfo(current_ip,nil)
      append_to_file("#{host_name[0][2]} - #{current_ip} - #{mac_addr}\n")
      

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

      【讨论】:

        猜你喜欢
        • 2012-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 2014-08-20
        • 1970-01-01
        • 2010-10-11
        相关资源
        最近更新 更多