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?

  • 4
    Try dig -x +short (the tailing . is part of the full domain name, BTW) Sep 3, 2013 at 20:54
  • You should make that an answer - that's exactly perfect.
    – JasonG
    Sep 3, 2013 at 21:32

2 Answers 2


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)


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

$ host domain name pointer localhost.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .