c has asked for the wisdom of the Perl Monks concerning the following question:

I read over How to find IP address from hostname? and found it helpful and brought me somewhat up to speed on using 'gethostbyname'. I am trying to evaluate whether a hostname (fqdn or otherwise) is able to resolve to an ip address (through dns or an /etc/hosts file).
I am able to use gethostbyname for hosts that resolve properly, however when a bogus name is presented as the hostname argument, the script errors out. i would rather it come back false such that i can say:

print "It doesnt resolve\n" unless ($ip);

I am toying around with the following code:

#!/usr/bin/perl -w use strict; use Socket; my $host = "noresolve"; my $i = gethostbyname($host); my $ip = inet_ntoa($i); print "Failure!\n" unless ( $ip );

humbly -c

Replies are listed 'Best First'.
Re: testing for ip resolutions of a hostname
by idnopheq (Chaplain) on Aug 28, 2001 at 21:42 UTC
    UPDATE: Oops ... slip 'o the mouse.

    Do some error checking in your lookups. Makes life much simpler, IMHO.

    #!/usr/bin/perl -w use strict; use Socket; my $host = "noresolve"; my $i = gethostbyname($host) or die "Failure to resolve $host: $!\n"; my $ip = inet_ntoa($i) or die "Failure to resolve $host: $!\n";

    HTH
    --
    idnopheq
    Apply yourself to new problems without preparation, develop confidence in your ability to to meet situations as they arrise.

      I can't use the die statements since those will force the script to exit. I want it to continue on and perform other actions based on whether or not the hostname is able to resolve to an ip address.

      humbly -c

        Ah! The lightbulb dimly illuminates!

        Howzabout wrapping the lookup functions in a sub and replacing the 'die's with returns. Untested, BTW ... hopefully no typos ...

        my $ip = lookup ( $host ) or warn "Cannot resolve $host!\n"; sub lookup { my $host = shift; my $i = gethostbyname($host) or return undef; my $ip = inet_ntoa($i) or return undef; return $ip; }

        HTH
        --
        idnopheq
        Apply yourself to new problems without preparation, develop confidence in your ability to to meet situations as they arrise.