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.