Hi Marco,

Here is another way to do it:

#!/usr/bin/perl
use strict;
use warnings;
my $ip = "127.0.0.1";
if ($ip =~
/^127\.0\.0\.([\d]|[1-9][\d]|[1][\d][\d]|[2]([0-4][\d]|[5][0-4]))$/) {
 print "IP Matched!\n";;
} else {
 print "No Match!\n";
}

On Tue, Nov 30, 2010 at 11:21 AM, Rob Dixon <rob.di...@gmx.com> wrote:

>  On 29/11/2010 23:46, John W. Krahn wrote:
>
>> Kammen van, Marco, Springer SBM NL wrote:
>>
>>> Dear List,
>>>
>>
>> Hello,
>>
>> I've been struggeling with the following:
>>>
>>> #!/usr/bin/perl
>>>
>>> use strict;
>>> use warnings;
>>>
>>> my $ip = ("127.0.0.255");
>>>
>>> if ($ip =~ /127\.0\.0\.[2..254]/) {
>>> print "IP Matched!\n";;
>>> } else {
>>> print "No Match!\n";
>>> }
>>>
>>> For a reason i don't understand:
>>>
>>> 127.0.0.1 doesn't match as expected...
>>> Everything between 127.0.0.2 and 127.0.0.299 matches...
>>> 127.0.0.230 doesn't match...
>>>
>>> What am I doing wrong??
>>>
>>
>> As Rob said [2..254] is a character class that matches one character (so
>> "127.0.0.230" should match also.) You also don't anchor the pattern so
>> something like '765127.0.0.273646' would match as well. What you need is
>> something like this:
>>
>> #!/usr/bin/perl
>>
>> use strict;
>> use warnings;
>>
>> my $ip = '127.0.0.255';
>>
>> my $IP_match = qr{
>> \A # anchor at beginning of string
>> 127\.0\.0\. # match the literal characters
>> (?:
>> [2-9] # match one digit numbers 2 - 9
>> | # OR
>> [0-9][0-9] # match any two digit number
>> | # OR
>> 1[0-9][0-9] # match 100 - 199
>> | # OR
>> 2[0-4][0-9] # match 200 - 249
>> | # OR
>> 25[0-4] # match 250 - 254
>> )
>> \z # anchor at end of string
>> }x;
>>
>> if ( $ip =~ $IP_match ) {
>> print "IP Matched!\n";;
>> }
>> else {
>> print "No Match!\n";
>> }
>>
>>
>> Or, another way to do it:
>>
>> #!/usr/bin/perl
>>
>> use strict;
>> use warnings;
>>
>> use Socket;
>>
>> my $ip = inet_aton '127.0.0.255';
>>
>> my $start = inet_aton '127.0.0.2';
>> my $end = inet_aton '127.0.0.254';
>>
>>
>> if ( $ip ge $start && $ip le $end ) {
>> print "IP Matched!\n";;
>> }
>> else {
>> print "No Match!\n";
>> }
>>
>
> This regex solution allows the IP address 127.0.0.01, which is out of
> range.
>
> - Rob
>
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>
>

Reply via email to