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

I am a perl newbie so please forgive....
I am grabbing a longIP address from a database, but I'm not sure how to convert it into the string dot notation. Anyone have clue? Thanks.

Replies are listed 'Best First'.
Re: convert longIP to stringIP
by tachyon (Chancellor) on Sep 12, 2003 at 16:02 UTC

    Is his FAQ what you want?

    use Socket; $iaddr = inet_aton("127.1"); # or whatever address $name = gethostbyaddr($iaddr, AF_INET);

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: convert longIP to stringIP
by Juerd (Abbot) on Sep 12, 2003 at 16:33 UTC

    This "longIP" is a valid IP already. You probably do not need to convert it.

    Converting it is easy if you tread the IP as an IP :)

    use Socket qw(inet_aton inet_ntoa); print inet_ntoa(inet_aton('2130706433'));

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

      Juerd,
      Thanks...however my long number is negative and it doesnt seem to work?
      My number is -1675066731. Any ideas?

        Try this:

        use Socket qw(inet_aton inet_ntoa); my $num = -1675066731; print inet_ntoa(inet_aton(hex(sprintf "%x", $num))); __DATA__ 156.40.130.149

Re: convert longIP to stringIP
by bear0053 (Hermit) on Sep 12, 2003 at 15:42 UTC
    DO you mean you are grabbing an ip address like this: 208.196.93.26 or is a hex number....post some data examples and you want to store it in a perl variable like this: 208.196.93.26 ??? What are you using to retrieve the data from the DB? You shouldn't have to worry about converting
Re: convert longIP to stringIP
by NetWallah (Canon) on Sep 12, 2003 at 21:12 UTC
    Aah - yes - I've run into this before.
    The Database returns signed 32-bit integers. The high IP addresses show up as negative integers.

    I would recommend using a module to handle IP addresses - my favourite is NetAddr::IP which works admirably but it won't solve your problem - you need a little more magic..

    Your problem can be solved using this :

    $n = get_number_from_database(); my $ip = NetAddr::IP->new($n < 0 ? 2**32 + $n : $n); # $ip now contain and IP object which can be printed , # or converted to binary, or checked for # subnet membership.
    (Thanks to Luis E. Muņoz, author of NetAddr::IP, for the original tip)

      Thanks NetWallah. I was about to post the tip myself ;)

      I'll be adding this to ->new as soon as I get the time...

      Best regards

      -lem, but some call me fokat