Created
September 18, 2014 13:05
-
-
Save NeuronQ/08cdc0f04aed17921eaf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$ip = '2001:df0:1e::'; | |
$ip2 = '2001:df0:1f::'; | |
$prefix_len = 48; | |
/** | |
* dtr_pton | |
* | |
* Converts a printable IP into an unpacked binary string | |
* | |
* @author Mike Mackintosh - mike@bakeryphp.com | |
* @param string $ip | |
* @return string $bin | |
*/ | |
function dtr_pton( $ip ){ | |
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)){ | |
return current( unpack( "A4", inet_pton( $ip ) ) ); | |
} | |
elseif(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)){ | |
return current( unpack( "A16", inet_pton( $ip ) ) ); | |
} | |
throw new \Exception("Please supply a valid IPv4 or IPv6 address"); | |
return false; | |
} | |
/** | |
* dtr_ntop | |
* | |
* Converts an unpacked binary string into a printable IP | |
* | |
* @author Mike Mackintosh - mike@bakeryphp.com | |
* @param string $str | |
* @return string $ip | |
*/ | |
function dtr_ntop( $str ){ | |
if( strlen( $str ) == 16 OR strlen( $str ) == 4 ){ | |
return inet_ntop( pack( "A".strlen( $str ) , $str ) ); | |
} | |
throw new \Exception( "Please provide a 4 or 16 byte string" ); | |
return false; | |
} | |
function ipv6_p_mask_from_prefix_len($prefix_len) { | |
$len = 128; | |
$chars = array_fill(0, $len, '1'); | |
while ($prefix_len--) $chars[$len - $prefix_len] = '0'; | |
$bin_str = implode('', $chars); | |
$bin_strs16 = str_split($bin_str, 16); | |
$r = ''; | |
foreach ($bin_strs16 as $bs) { | |
$r .= dechex(bindec( $bs )); | |
} | |
return implode(':', str_split($r, 4)); | |
} | |
//$mask = ipv6_p_mask_from_prefix_len(4); | |
//$mask_n = dtr_pton($mask); | |
$ip_n = dtr_pton($ip); | |
$ip2_n = dtr_pton($ip2); | |
function is_addr_in_network($network_start_addr, $prefix_len, $ip) { | |
$network_start_addr = dtr_pton($network_start_addr); | |
$mask = dtr_pton(ipv6_p_mask_from_prefix_len($prefix_len)) && $network_start_addr; | |
$ip = dtr_pton($ip); | |
return $ip && $mask == $mask; | |
} | |
//< ipv6_p_mask_from_prefix_len(48) | |
//< is_addr_in_network('2001:df0:1e::', 113, '2001:df0:1e::1') | |
//< is_addr_in_network('::ffff:1.0.128.0', 113, '::ffff:1.0.120.2') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment