note 9546 deleted from function.ip2long by felipe

From: Date: Sat, 29 Dec 2007 19:06:40 +0000
Subject: note 9546 deleted from function.ip2long by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134178@lists.php.net to get a copy of this message
Note Submitter: jna at retina dot net ---- One thing PHP lacks is a way to compare two IP addresses, which I thought might be under this function, but isn't. Here goes: function testip($range,$ip) { $result = 1; # IP Pattern Matcher # J.Adams <jna@retina.net> # # Matches: # # xxx.xxx.xxx.xxx (exact) # xxx.xxx.xxx.[yyy-zzz] (range) # xxx.xxx.xxx.xxx/nn (nn = # bits, cisco style -- i.e. /24 = class C) # # Does not match: # xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported) if (ereg("([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)",$range,$regs)) { # perform a mask match $ipl = ip2long($ip); $rangel = ip2long($regs[1] . "." . $regs[2] . "." . $regs[3] . "." . $regs[4]); $maskl = 0; for ($i = 0; $i< 31; $i++) { if ($i < $regs[5]-1) { $maskl = $maskl + pow(2,(30-$i)); } } if (($maskl & $rangel) == ($maskl & $ipl)) { return 1; } else { return 0; } } else { # range based $maskocts = split("\.",$range); $ipocts = split("\.",$ip); # perform a range match for ($i=0; $i<4; $i++) { if (ereg("\[([0-9]+)\-([0-9]+)\]",$maskocts[$i],$regs)) { if ( ($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) { $result = 0; } } else { if ($maskocts[$i] <> $ipocts[$i]) { $result = 0; } } } } return $result; }

« previous php.notes (#134178) next »