Convert Integer To IP Address

2010-05-26

Of an acquaintance, I got the assignment to write a function that converts an integer to an IP address. An IP address is really just another way to represent an integer. Below is an example of the solution I came up to. This code is written in Perl.

#!/usr/bin/perl
my($int) = $ARGV[0]; #Receives an integer as an argument.
my(@ip); #An array that holds the octets of the IP address.
for(my($i) = 0; $i < 4; $i++)
{
  $ip[$i] = $int % 256;
  $int = ($int - $ip[$i]) / 256;
}
print($ip[3].".".$ip[2].".".$ip[1].".".$ip[0]."\n");
  • Thanks so much for this code. It helped me integrate into a slightly bigger set for meaningful information.