Re: Regular Expresion Work on IP address
| From: | Dev | Date: | Wed, 04 Dec 2002 20:29:53 +0000 |
| Subject: | Re: Regular Expresion Work on IP address | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-127031@lists.php.net to get a copy of this message | ||
Well after reading John'ss and DL Neil's replys i came up with 2 functions.
The first is to check to see if the entry is a valid IP address and the Next is to determine if it is a Private Network IP or not!.
You can see this in action at:
http://www.my-tangled-web.net/codebank/code/ip_check.php
and the sorce for that page is at:
http://www.my-tangled-web.net/codebank/getsource.php?dir=&file=ip_check.php
Please if you test it and find a problem let me know!
Thanks
function ipcheck($ip_chk){
$parts=explode(".",$ip_chk);
if (preg_match ("/^([01]?\d\d?|2[0-4]\d|25[0-4])\.([01]?\d\d?|2[0-4]\d|25[0-4])\.([01]?\d\d?|2[0-4]\d|25[0-4])\.([01]?\d\d?|2[0-4]\d|25[0-4])$/", $ip_chk))
{
if($parts[0]==0 || $parts[0]>=255 ||$parts[1]>=255 || $parts[2]>=255 || $parts[3]>=255){
$ip_state="0";
}
elseif($parts[0]<255 && $parts[1]<255 && $parts[2]<255 && $parts[3]<255){
$ip_state="1";
}
}
else {
$ip_state=0;
}
$this="that";
return $ip_state;
}
function net_check($ip_2_chk){
$parts=explode(".",$ip_2_chk);
if($parts[0]==10){
$network="internal";
}
elseif($parts[0]==172 && $parts[1]>=16 || $parts[1]<=31){
$network="internal";
}
elseif($parts[0]==192 && $parts[1]==168){
$network="internal";
}
else {
$network="external";
}
return $network;
};
At 07:47 PM 12/4/2002 +0000, DL Neil wrote:
John, I think it'd be hard to verify the range with a regex. ip2long and long2ip do not validate. So, an option would be to write your own little function that splits the $ip on the period, verifies there are 4 parts, then checks that each part is between 1 and 255 inclusive. My other post on the subject notwithstanding, I agree. When I get time/when I get a round tuit, I'd like to do a performance test on the (short) IP RegEx against what you have outlined: explode against "." run resultant array through 0-255 validation function - and still have the semantic issues of 0.0.0.0, etc... Meantime, will sit here whistling and quietly muttering into my beard (and dreaming of tuits), =dn -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php