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

Trying to get this to accept an ip address as an argument and it doesnt work. If I eliminate the $addy variable and just put in an ip address here: my $client = gethostbyaddr(111.11.111.111, AF_INET); # get name it works but cant get it to accept a variable in the below:
use Socket; use strict; my $addy = shift || die "Enter a IP address"; my $client = gethostbyaddr($addy, AF_INET); # get name if ($client) { print $client, "\n\a"; } else { print "no\n"; }
The output keeps coming back with "no" even though I put in a valid ip address. It should give me back the name to the server. Why cant I pass the $addy variable in the argument. Please help me fix this.

Replies are listed 'Best First'.
Re: variable not passing
by gaal (Parson) on Dec 07, 2004 at 18:31 UTC
    You need to call inet_aton on your string first. See Socket.
      Thanks I tried this and still no luck:
      use Socket; use strict; my $addy = shift || die "Enter a IP address"; my $port = getservbyname('smtp', 'tcp'); my $sin = sockaddr_in($port,inet_aton($addy)); my $client = gethostbyaddr($sin, AF_INET); # get name if ($client) { print $client, "\n\a"; } else { print "no\n"; }
        You don't need this sin stuff here. Try your original code, but with the following replacement:

        # this: my $client = gethostbyaddr(inet_aton($addy), AF_INET); # get name # instead of: my $client = gethostbyaddr($addy, AF_INET); # get name

        It worked for you with the variable not received from the user because you weren't using quote marks, and you were getting a v-string (a deprecated feature, actually). Your luck was that a v-string is a lot like an inet_aton()-ed string :)

        Incidentally, why are you using Socket? Unless you want to use low-level stuff for learning or fine control, you are probably better off using IO::Socket. See perlipc, also.

Re: variable not passing
by Eimi Metamorphoumai (Deacon) on Dec 07, 2004 at 19:01 UTC
    Use
    my $client = gethostbyaddr(inet_aton($addy), AF_INET); # get name
    instead. You'll findthat if you used "111.11.111.111" instead of 111.11.111.111 (note the quotes), you would have gotten the same result. But it turns out that perl handles dotted quads (or actually any dotted decimals) as a particular kind of string constant (called a Version String, search for it in perldata for more info) that doesn't need processing through inet_aton.