in reply to Re: gethostbyname not working
in thread gethostbyname not working

This gets me further, when I print them out however, I get numbers that are no relative the the IP address, or even close. for instance,
my $hostname = ''; my $addr = (gethostbyname($hostname))[0]; my ($a,$b,$c,$d) = unpack('C4',$addr); print "$a.$b.$c.$d\n";

This prints out:
which is not even close to yahoo's IP (I know yahoo has a large subnet, but this doesn't even start with the same number). Any ideas?

Replies are listed 'Best First'.
Re^3: gethostbyname not working
by tadman (Prior) on Mar 27, 2001 at 23:19 UTC
    Using unpack here seems a bit awkward. Why not use the builtins from Socket and simplify?
    use Socket; my $hostname = ''; print inet_ntoa(inet_aton($hostname)),"\n";
    inet_aton converts from "ASCII" to "Network", and as a bonus will resolve host names. The reverse, inet_ntoa, will do the inverse, though it will always give you a dotted IP and not the name. To find that out, you will have to use Net::DNS.

    You will note that it puts out different answers on occasion, though, because there are many possible addresses to choose from, and they are selected at random, which is called "Round Robin DNS".

    As a side note, this code will die "Bad arg length..." if fed an invalid or unresolvable address. This can be fixed by splitting it into two steps and verifying that inet_aton() actually returned something.
Re: Re: Re: gethostbyname not working
by myocom (Deacon) on Mar 27, 2001 at 02:18 UTC

    Oops, my mistake; it's the last bit of gethostbyname, not the first. Good catch. I've updated my node above.