Hello Dev,

> Now I am continuing on with the same script and I need to check for valid
> IP address form.
> Currently I have:
>
> $ip="255.255.255.0";
> if (preg_match ("/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/", $ip))
{
>      print "Good Ip";
> } else {
>      print "Bad Ip";
> }
>
> This does work kinda.  It checks to see if the 4 sets of  numbers are well
> there and numbers.
> The problem I am having is that it does not check to see if the IP is in a
> proper range ie less than 255.255.255.255
> So you could enter 256.256.256.999 and it will say that it is a good IP.
>
> Any clue how I would change it to check for that????


I'm reading my way through Friedl's, "Mastering Regular Expressions",
O'Reilly, 2002. This is discussed in pp187-9, but I haven't had a chance to
'play' with it yet (!) and indeed he comments that it is one of those topics
that you can attempt to refine and refine, but may be equally well off by
sticking with what you have (surround the individual octet values with
parentheses and then perform the semantic checking in PHP - as you discuss).

What he comes up with observes the shorter range of digits for the first two
digit positions of a (possible) three digit octet expression (in decimal),
eg the first digit is either 0, 1, or 2 or not present at all.

So if the first digit is a 1, then the next digits can be anything.
If the first digit is a 0 or a space/non-existent then...
However if the first digit is a 2, then the next digit may not exceed 5
[0-5]. If it is 5 then the last digit is similarly constrained, but if the
second digit is less than 5, the third can be any digit.
NB the 0.0.0.0 and 255.255.255.255 issues remain
Thus the main component (handling each octet) is the basic code:

([01]?\d\d?|2[0-4]\d|25[0-5])\.

which in English comes out as something like:
a zero and a one may be present and followed by a digit and possibly another
digit, or
a two will be present, followed by a digit in the range 0 through 4,
followed by another digit, or
a two and a five will be present followed by a digit in the range 0 through
5,
and then a dot/separator.

This turns the whole shebang into:

^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2
[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$

I'm sorry, but that's going to be diabolic to read after the email has had
at it.

The ^ and $, begin/end are necessary to ensure that there aren't
over-running digits afore or aft of the IP addr.

NB this is NOT tested (by me). I'm not sure if this code (the options in
particular), as it is written, can be pasted straight into PHP's version of
PCRE. YMMV!

If you try it, please send feedback,
=dn


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to