Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Regexp: Private IP Addresses

by markkawika (Monk)
on Aug 25, 2009 at 18:22 UTC ( #791149=note: print w/replies, xml ) Need Help??

in reply to Regexp: Private IP Addresses

You can use Net::IP::Match::Regexp to do this:

use Net::IP::Match::Regexp qw( create_iprange_regexp match_ip ); my $regexp = create_iprange_regexp( qw( ) ); if (match_ip($my_ip, $regexp)) { ... }

Replies are listed 'Best First'.
Re^2: Regexp: Private IP Addresses
by Sewi (Friar) on Aug 25, 2009 at 18:36 UTC
    If you know you have an IP-address (got it from a network socket, for example), it would be much more efficient to match it with a one-line regexp:
    If you got it from a non-network input (like a user form), don't trust in it, it may be 10.9999.1234.666.
      Yes, using a regular expression is "much more efficient", but yours is in some cases, as you point out, incorrect. And using Net::IP::Match::Regexp you can still do more than sixty seven thousand comparisons per second (on my old and rusty laptop, anyway) if the regexp is initialized once only. So what do you want:
      • Superfast and possibly incorrect, or
      • Fast and correct?
      $ cat use strict; use warnings; use Net::IP::Match::Regexp qw( create_iprange_regexp match_ip ); use Benchmark qw / cmpthese /; my $regexp_init_once = create_iprange_regexp( qw( ) + ); sub netip { my $regexp = create_iprange_regexp( qw( + ) ); return ( match_ip( $_[0], $regexp ) ); } sub netip_init_once { return match_ip( $_[0], $regexp_init_once ); } sub regexp { return $_[0] =~ /^(10\.\d+|172\.(1[6-9]|2\d|3[0-1])|192\.168)(\.\d+) +{2}$/; } cmpthese( -1, { 'netip' => sub { netip('') }, 'netip_init_once' => sub { netip_init_once('') }, 'regexp' => sub { regexp('') }, } ); __END__ $ perl Rate netip netip_init_once reg +exp netip 2438/s -- -96% -1 +00% netip_init_once 67622/s 2674% -- - +95% regexp 1390157/s 56918% 1956% + --
      No matter how great and destructive your problems may seem now, remember, you've probably only seen the tip of them. [1]

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://791149]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2018-06-25 17:36 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (128 votes). Check out past polls.