Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to find out how to take in a hostname and pop out an ip address (reverse dns lookup).

I came up with this but I'm not too sure it's safe across different linux distros:

nslookup $ip|grep "name ="|sed 's/^.*name = //'| sed '$s/\.$//'

It appears to be okay. The call to nslookup gives:

$ nslookup
Address:  name = localhost.

So we grep to remove the lines that don't give the hostname. Then we use said to remove everything before "name = " and remove the . at the end. If there are more than one line for whatever reason, then we just take the first one only. That gives 'localhost' There must be some better way to do this?

share|improve this question
Try dig -x +short (the tailing . is part of the full domain name, BTW) – Stéphane Chazelas Sep 3 '13 at 20:54
You should make that an answer - that's exactly perfect. – JasonG Sep 3 '13 at 21:32
up vote 7 down vote accepted

nslookup is a bit of a deprecated command, in favour of the dig command by the ISC.

With dig, you would write it:

dig -x +short

Alternatively, you could do:

perl -MSocket -le 'print((gethostbyaddr(inet_aton(""), AF_INET))[0])'

which would use the system's resolver to get you the info (which in turn might use /etc/hosts, DNS, NIS+, LDAP... as per /etc/nsswitch.conf, not only DNS as dig or nslookup would)

share|improve this answer
Thanks Stephane - perfect - just the info I needed. – JasonG Sep 4 '13 at 17:55

You could try the host command which will give you an output similar to:

$ host domain name pointer localhost.
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.