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, 13 years and 60 days ago. Viewed 8,893 times. #4
[diff] [history] [edit] [rdf]

Change a 32-bit integer into an IP address

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


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";
            $out = $element;
    # that's it
    return $out;


Peter Hallam dropped me a line to say:


I came across your integer to IP address article at >> 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
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: | Copyright 2000-2002 Matthias L. Jugel and Stephan J. Schmidt