0

Unix: How to Test ip Address is resolved to name.

I need to check whether ip address can be resolved to name using DNS entry via shell script.

Code:

DNS_Lookup()
{
        LOOKUP=$(nslookup $1)
        FAIL_COUNT=$(echo $LOOKUP | grep "** server can't find " | wc -l);
        if [ $FAIL_COUNT -eq 1 ];then
            echo "Unable to resolve DNS for $1" 
        else
            echo "IP:$1 DNS Name:$(echo $LOOKUP | grep -v nameserver | cut -f 2 | grep name | cut -f 2 -d "=" | sed 's/ //')" 
            return 0
        fi
} 

DNS_Lookup 192.168.27.191

The above code is not working in all possible cases. OS:CentOS

2

You can use the getent command with the hosts parameter like this:

getent hosts www.google.com

And count how many results this gets:

getent hosts www.google.com | wc -l

getent uses the Name Service Switch libraries to do various name lookups. With the second parameter you can define which kind of db you want to lookup. Check man getent for details.

  • Thanks will this command work in all OS (i.e) Unix ?? – Ram Aug 29 '13 at 14:20
  • I'm not sure about -all- OS, but it works on Linux, FreeBSD and Solaris which already covers quite a lot. – replay Aug 29 '13 at 14:23
0

Showing two possible approaches which are portable.

#!/bin/sh

reverseDNS=$(host 8.8.8.8) 
if [ $? != 0 ]; then 
    printf '%s\n' "Reverse DNS [FAILED]"
else
    printf '%s\n' "Reverse DNS [OK]"
fi

###### nslookup ##########

nslookup_func(){

    nslookup=$(nslookup google.com)

    if [ "$nslookup" = ";; connection timed out; no servers could be reached" ]; then
        printf '%s\n' "nslookup [FAILED]"
    else
        printf '%s\n' "nslookup [OK]"
    fi
}

nslookup_func 
  • Thank you ... I have tried the first approach already in CentOS it returns the exit code always as 0. But in RHEL it should works fine. For second approach there are lot of possible errors please see the link h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V51B_HTML/MAN/… So that i am trying for alternative ..... – Ram Aug 29 '13 at 14:58
  • That is the manpage of nslookup. I don't know what your alternative is or what you are referring to with the link. – Valentin Bajrami Aug 29 '13 at 15:08
  • I referring your if check "if [ "$nslookup" = ";; connection timed out; no servers could be reached" ];" which checks for only two errors but there are lot more errors can be shown ..... – Ram Aug 30 '13 at 4:42
  • I referring your if check "if [ "$nslookup" = ";; connection timed out; no servers could be reached" ];" which checks for only two errors but there are lot more errors can be shown ..... – Ram Aug 30 '13 at 5:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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