For When You Can't Have The Real Thing
[ start | index | login ]
start > perl > integer to IP address

integer to IP address

Created by dave. Last edited by dave, 7 years and 70 days ago. Viewed 5,547 times. #4
[diff] [history] [edit] [rdf]
labels
attachments

Change a 32-bit integer into an IP address

$ echo 1088834552 | perl -ne 'print $_>>24 ,".",$_<<8>>24,".",$_<<16>>24,".",$_<<24>>24,"\n"'
64.230.75.248

(>>Source)

sub int2ip
{
    local ($in, $element, $mask, $out);
    $in = shift (@_);
    # parse by octet
    foreach $mask (24, 16, 8, 0)
    {
        # mask the current element
        $element = $in & (255 * (2**$mask));
        $element = $element / (2**$mask);
        # sanity check
        &die("$in looks bogus: mask $mask results $element") if ($element > 255);
        # glue it on
        if ($mask < 24)
        {
            $out = "$out.$element";
        }
        else
        {
            $out = $element;
        }
    }
    # that's it
    return $out;
}

Update

Peter Hallam dropped me a line to say:

Hi,

I came across your integer to IP address article at >>http://wiki.xdroop.com/space/perl/integer+to+IP+address and realised there's a much simpler solution available:

perl -E 'say join ".", unpack "C4", pack "N", 1088834552'

The -E assumes you have a perl version of 5.10.0 or above, otherwise:

perl -e 'print join ".", unpack "C4", pack "N", 108883455; print "\n"'

Kind Regards, Pete

I'll take his word for it, this is beyond my perl-fu right now.

no comments | post comment

Virtual Dave Megaplex:

Internet Explorer 6 Users >>Click Here

(read this note about local search)

Logged in Users: (0)
… and 3 Guests.


Editing: snipsnap-help, Image Macro

(Et auditum est, et idcirco ego nunc simulare)

Installed 6 years and 336 days ago
Powered By >>SnipSnap Version 1.0b1-uttoxeter

This is a collection of techical information, much of it learned the hard way. Consider it a lab book or a /info directory. I doubt much of it will be of use to anyone else.

Useful:


snipsnap.org | Copyright 2000-2002 Matthias L. Jugel and Stephan J. Schmidt