Hi monks,

I work with a database that stores a pool of IP addresses in numeric form. If any of you have to deal with something similar, here's a handy little function that can convert IP addresses into numeric form.

sub ipToNum { my $ip = shift; my @octets = split(/\./, $ip); my $ip_number = 0; foreach my $octet (@octets) { $ip_number <<= 8; $ip_number |= $octet; } return $ip_number; }

So, for example, if you feed it 192.168.0.1, it will return 3232235521.

- cerror

Replies are listed 'Best First'.
Re: IP to numeric value.
by rhesa (Vicar) on Jul 11, 2007 at 23:51 UTC
    The Socket module provides inet_aton and inet_ntoa, which wrap your network library.

    I'd write your function like this:

    use Socket qw/ inet_aton /; sub ipToNum { my $ip = shift; return unpack "N", inet_aton( $ip ); }

    If your database is MySQL, it also has native versions of those functions, so you could run queries like

    select inet_ntoa( ipnum ) from iptable
      Ah, thank you.

      I'm still rather new to perl, so I guess I inadvertently spend a little time reinventing the wheel.

      Though, I suppose it's always a good exercise to figure out how those sort of functions work on your own.

      - cerror
        There's nothing wrong with reinventing the wheel, so long as you're know you're doing it, and are clear on the reasons why you're doing it. To learn how something works is a pretty good reason.
        Absolutely, what Mutant said. It's always good to practice. Bit-manipulation functions are low-level enough that it takes some time to get them committed to memory.

        As for reinventing the wheel, you don't always realise you're doing it until someone else points out the existing ones.

        As a matter of fact, I just discovered an ip2num function in one of my own libraries (written about 3 years ago). I guess I didn't know about those native functions back then either :-)