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

Hello, I am using the function gethostbyname() to get the IP address of a hostname. heres an example of what I am doing.
my $hostname = 'yahoo.com'; my $ip = gethostbyname($hostname); print "$ip\n";
This returns meaningless data, such as: Øsló or any other random ASCII string, I remember this working but now it isn't ... Any suggestions?

Replies are listed 'Best First'.
Re: gethostbyname not working
by myocom (Deacon) on Mar 27, 2001 at 01:59 UTC

    As you will see in the docs, gethostbyname returns a list, the last element of which is the IP address in packed format. You'll need to unpack it first, like so:

    my $hostname = 'yahoo.com'; my $addr = (gethostbyname($hostname))[4]; # Or, as Anonymous Monk points out below, you could simply use: # my $addr = gethostbyname($hostname); my ($a,$b,$c,$d) = unpack('C4',$addr); print "$a.$b.$c.$d\n";

    Update: Corrected which element of gethostbyname returns the address.

    Update 2: Added AM's advice.

      You can simply use
      my $addr = gethostbyname($hostname);
      instead of
      my $addr = (gethostbyname($hostname))[4];
      When used in scalar context, gethostbyname returns the address, which would have prevented your earlier bug.
        This is what I did at first, that was the problem (if you look at my original post). what's the difference?

        Ah, so it does! Thanks for the tip!

      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, yahoo.com
      my $hostname = 'yahoo.com'; my $addr = (gethostbyname($hostname))[0]; my ($a,$b,$c,$d) = unpack('C4',$addr); print "$a.$b.$c.$d\n";

      This prints out: 121.97.104.111
      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?
        Using unpack here seems a bit awkward. Why not use the builtins from Socket and simplify?
        use Socket; my $hostname = 'yahoo.com'; 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.

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