note 104253 added to function.ip2long

From: Date: Fri, 03 Jun 2011 15:44:38 +0000
Subject: note 104253 added to function.ip2long
Groups: php.notes 
Request: Send a blank email to php-notes+get-180224@lists.php.net to get a copy of this message
Using the ip2bin code from above, I created two functions that can be used to check whether a given IPv4 or IPv6 IP matches an IPv4 or IPv6 netmask: <?php // Returns true if IP is in IPv4/IPv6 CIDR range // and returns false otherwise function isIPinCIDRBlock($cidr, $ip) { // Split CIDR notation list ($net, $mask) = split ("/", $cidr); // Convert to binary string value of 1s and 0s $netAsBinary = ip2bin($net); $ipAsBinary = ip2bin($ip); // Return false if netmask and ip are using different protocols if (strlen($netAsBinary) != strlen($ipAsBinary)){ return false; } // Compare the first $mask bits for($i = 0; $i < $mask; $i++){ // Return false if bits don't match if ($netAsBinary[$i] != $ipAsBinary[$i]){ return false; } } // If we got here, ip matches net return true; } // Converts IP in human readable format to binary string function ip2bin($ip){ // Handle IPv4 IP if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false){ return base_convert(ip2long($ip),10,2); } // Return false if IP is neither IPv4 nor a IPv6 IP if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false){ return false; } // Convert IP to binary structure and return false if this fails if(($ipAsBinStructure = inet_pton($ip)) === false) { return false; } $numOfBytes = 16; $ipAsBinaryString = ''; // Convert IP to binary string while ($numOfBytes > 0){ // Convert current byte to decimal number $currentByte = ord($ipAsBinStructure[$numOfBytes - 1]); // Convert currenty byte to string of 1 and 0 $currentByteAsBinary = sprintf("%08b", $currentByte); // Prepend to rest of IP in binary string $ipAsBinaryString = $currentByteAsBinary.$ipAsBinaryString; // Decrease byte counter $numOfBytes--; } return $ipAsBinaryString; } ?> ---- Server IP: 194.153.94.10 Probable Submitter: 130.59.16.9 ---- Manual Page -- http://www.php.net/manual/en/function.ip2long.php Edit -- https://master.php.net/note/edit/104253 Del: integrated -- https://master.php.net/note/delete/104253/integrated Del: useless -- https://master.php.net/note/delete/104253/useless Del: bad code -- https://master.php.net/note/delete/104253/bad+code Del: spam -- https://master.php.net/note/delete/104253/spam Del: non-english -- https://master.php.net/note/delete/104253/non-english Del: in docs -- https://master.php.net/note/delete/104253/in+docs Del: other reasons-- https://master.php.net/note/delete/104253 Reject -- https://master.php.net/note/reject/104253 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#180224) next »