1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

Getting the Domain From a Hostname


The question was asked: "Given a hostname, how do I get the domain?" There are a few simple solutions to this, but they're all wrong.

So, let's clarify this a bit. You're given a hostname, like computer7.drafting.design.company.com, and you want to extract from that just the domain name, in this case company.com.

The first obvious answer is to use a regular expression. You can get a section of the string from the end of the string to either the second dot from the end, or the beginning of the string. Let's try that.

>> hostname = "computer7.drafting.design.company.com"
=> "computer7.drafting.design.company.com"
>> domain = hostname.match(/(\.|^)([^\.]+\.[^\.]+$)/)[2]
=> "company.com"

That seems to work, but to be honest, that's pretty ugly. The regular expression is a real eyesore, it's not immediately clear what it does exactly. So let's use the split method instead.

>> hostname = "computer7.drafting.design.company.com"
=> "computer7.drafting.design.company.com"
>> domain = hostname.split('.')[-2..-1].join('.')
=> "company.com"

This is much more clear. Split it on the dots, take the last two, join them again with dots. But in the quest to make this more clear is Ruby-like, something important was missed. What do you do with a hostname like computer7.drafting.design.company.co.uk? Here, what is the "domain?"

The TLD is .uk, but the very common second level domain of .co is being used here. And clearly, what's needed is the string bbc.co.uk. So in order to get this, we have to do some DNS queries. And here, we'll define the "domain" that we're looking for here as the smallest part of this string that will resolve to an address with a DNS query. The TLDs and second-level domains like the one used here will not resolve to addresses, and aren't what we're looking for.

So first things first, let's install the net-dns gem.

$ gem install net-dns

Next, this little method will do what we need. It splits the string, reverses the list and re-builds the domain from right to left until it finds something that resolves to an address. So, if you were to test something.company.co.uk, it would first try to resolve uk, then co.uk and finally company.co.uk.

def domain(hostname)
 domain = ''
 for p in hostname.split('.').reverse
    domain = p + (domain.empty? ? '' : ".#{domain}")
    break unless Resolver(domain).answer.empty?

 return domain

The shortest code is not always the best code. In this case, in order to be "correct," the code actually has to pull information from the DNS system in order to be "correct."

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Things Are Never As Easy As They Seem: Getting the Domain From a Hostname

©2014 About.com. All rights reserved.