note 104253 deleted from function.ip2long by danbrown
| From: | danbrown@php.net | Date: | Fri, 03 Jun 2011 16:09:20 +0000 |
| Subject: | note 104253 deleted from function.ip2long by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-180225@lists.php.net to get a copy of this message | ||
Note Submitter: php dot 1 dot haemmluk at spamgourmet dot com
----
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;
}
?>