4

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?

2
  • 4
    Try dig -x 127.0.0.1 +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

8

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)

0
2

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.

You must log in to answer this question.

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