Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 127.0.0.1
Server:     192.154.28.100
Address:    192.154.28.100#53

1.0.0.127.in-addr.arpa  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
4  
Try dig -x 127.0.0.1 +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
add comment

2 Answers 2

up vote 5 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 127.0.0.1 +short

Alternatively, you could do:

perl -MSocket -le 'print((gethostbyaddr(inet_aton("127.0.0.1"), 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
add comment

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

$ host 127.0.0.1
1.0.0.127.in-addr.arpa domain name pointer localhost.
share|improve this answer
add comment

Your Answer

 
discard

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.