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

Hello Monks!

I need to be able to convert integer versions of IPv4 address to the four octet version of the IP address. I have this script that works well but I need to embed this into a scriptlet in an RPM, so I was hoping someone could help stream-line it some.

#!/usr/local/bin/perl -w use strict; my $int = shift || 2130706433; # 127.0.0.1 my $quad4 = $int % 256; $int = int($int/256); my $quad3 = $int % 256; $int = int($int/256); my $quad2 = $int % 256; $int = int($int/256); my $quad1 = $int % 256; print "$quad1.$quad2.$quad3.$quad4\n";

Thanks!

Replies are listed 'Best First'.
Re: Integer IP address to Quad IPv4 address one liner or close to it?
by Fletch (Bishop) on Aug 06, 2009 at 17:43 UTC

    inet_ntoa and pack are your friends.

    $ perl -MSocket=inet_ntoa -le 'print inet_ntoa(pack("N",shift||2130706 +433))' 127.0.0.1 $ perl -MSocket=inet_ntoa -le 'print inet_ntoa(pack("N",shift||2130706 +433))' 3232235777 192.168.1.1

    Update: And since you've asked about the reverse:

    $ perl -MSocket -le 'print unpack("N",inet_aton(shift||"192.168.1.1")) +' 3232235777 $ perl -MSocket -le 'print unpack("N",inet_aton(shift||"192.168.1.1")) +' 127.0.0.1 2130706433

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Integer IP address to Quad IPv4 address one liner or close to it?
by BrowserUk (Patriarch) on Aug 06, 2009 at 17:40 UTC

    Like this?

    print join '.', unpack 'C4', pack 'N', 2130706433;; 127.0.0.1

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Ah Thanks! Would there be a equally straight forward solution for the reverse operation? You ...
      ./somescript.pl 127.0.0.1 2130705433
      ... ?

        You should probably use the functions in Socket who's names I can never remember, but this works for the dotted decimal form:

        print unpack 'N', pack 'C4', split '\.', '127.0.0.1';; 2130706433

        It doesn't work for those obscure forms that only hackers and scammers use: dotted-hex & dotted-octal.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.