在ruby中获取域名主机名

时间:2015-10-13 23:40:07

标签: ruby uri host

有没有办法在ruby中获取域名的主机名?

例如:

$ host api.heroku.com
api.heroku.com is an alias for api-default.herokussl.com.
api-default.herokussl.com is an alias for elb027033-298234319.us-east-1.elb.amazonaws.com.
elb027033-298234319.us-east-1.elb.amazonaws.com has address 23.23.76.65
elb027033-298234319.us-east-1.elb.amazonaws.com has address 23.21.240.208
elb027033-298234319.us-east-1.elb.amazonaws.com has address 107.22.242.236

主机将是最好的例子,因为它还会显示域/子域是否指向另一个主机,如amazonAWS等。

1 个答案:

答案 0 :(得分:1)

  

不如从ruby

执行host domain.com命令有用

我不同意......(但它确实涉及了解您想要的数据以及DNS如何工作)。

require 'resolv'

def host(address)
  Resolv::DNS.open do |dns|
    loop do
      ress = dns.getresources address, Resolv::DNS::Resource::IN::CNAME
      break if ress.empty?
      canonical_name = ress.first.name.to_s
      puts "#{address} is an alias for #{canonical_name}"
      address = canonical_name
    end

    ress = dns.getresources address, Resolv::DNS::Resource::IN::A
    addresses = ress.each do |r|
      puts "#{address} has address #{r.address.to_s}"
    end
  end
  return
end

host("api.heroku.com")