Search code examples
rubyurihost

Getting domain host name in ruby


Is there a possible way to get the domain's hostname in ruby?

For example:

$ 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

host would be the best example, because it'll also show if the domain/subdomain is pointing to another host like amazonAWS or etc.


Solution

  • not as useful as executing host domain.com command from ruby

    I beg to differ... (but it does involve knowing what data you want, and how DNS works).

    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")