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.

  • Nice job!

    However, there’s a small bug in ip2dec():

    The regex /./ should be /./

  • Nice job!

    However, there’s a small bug in ip2dec():

    The regex /./ should be /\./

  • What I meant to say was: The period in the regex needs to be escaped, i.e.

    /./ should be /./

    But backslashes are “eaten” when submitting a comment, so my comment above has the same bug as the code appears to have…

  • What I meant to say was: The period in the regex needs to be escaped, i.e.

    /./ should be /./

    But backslashes are “eaten” when submitting a comment, so my comment above has the same bug as the code appears to have…

  • Nice job!

    However, there’s a small bug in ip2dec():

    The regex /./ should be /./

  • What I meant to say was: The period in the regex needs to be escaped, i.e.

    /./ should be /./

    But backslashes are “eaten” when submitting a comment, so my comment above has the same bug as the code appears to have…

  • I like this cript verymuch for my design need thanks for puting it here

  • Jsevilla

    Muchas gracias por tu aportación, saludos desde México.