質問

私は、適切に発明されていないコンピューターがたくさんある環境にいます。基本的に、どの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, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][1]

getaddrinfo 関数は配列の配列を返します。詳細については、次のリンクで読むことができます。

Ruby ソケットのドキュメント

他のヒント

今日、DNS 逆引き参照も必要になりましたが、非常にシンプルな標準ソリューションを見つけました。

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

ひどい場合に役立つタイムアウトを使用しているようです。

これも機能します:

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

理由はわかりません gethostbyaddr も機能しませんでした。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top