IP address conversion with Perl

With Perl you can do many interesting transformations of IP-numbers. Below is two small examples allowing conversions from “IP quad” (xxx.xxx.xxx.xxx) format to a single decimal and back. The decimal format may be more convenient and efficient to store in a database.

  sub ip2dec ($) {
    return unpack N => pack CCCC => split /\\./ => shift;
  }

  sub dec2ip ($) {
    return join '.' => map { ($\_\[0\] >> 8\*(3-$\_)) % 256 } 0 .. 3;
  }

In CPAN you can find many modules aimed at using and manipulating IP-addressees.

Some include Net::IP and IP::Country.