Take the 2-minute tour ×

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

2 Answers 2

up vote 6 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


