How to check an IP address is within a range of two IPs in PHP? - with ipv6 support -
this duplicate of question: how check ip address within range of 2 ips in php?
however solution above question not support ipv6. there similar solution ipv6 support?
suggestions:
string inet_ntop ( string $in_addr ) this function converts 32bit ipv4, or 128bit ipv6 address (if php built ipv6 support enabled) address family appropriate string representation.
you should see,
string inet_pton ( string $address ) inet_ntop() example
<?php $packed = chr(127) . chr(0) . chr(0) . chr(1); $expanded = inet_ntop($packed); /* outputs: 127.0.0.1 */ echo $expanded; $packed = str_repeat(chr(0), 15) . chr(1); $expanded = inet_ntop($packed); /* outputs: ::1 */ echo $expanded; ?> comparing in range
the following 2 functions introduced in php 5.1.0, inet_pton , inet_pton. purpose convert human readable ip addresses packed in_addr representation. since result not pure binary, need use unpack function in order apply bitwise operators.
both functions support ipv6 ipv4. difference how unpack address results. ipv6, unpack contents a16, , ipv4, unpack a4.
to put previous in perspective here little sample output clarify:
// our example ip's $ip4= "10.22.99.129"; $ip6= "fe80:1:2:3:a:bad:1dea:dad"; // ip2long examples var_dump( ip2long($ip4) ); // int(169239425) var_dump( ip2long($ip6) ); // bool(false) // inet_pton examples var_dump( inet_pton( $ip4 ) ); // string(4) var_dump( inet_pton( $ip6 ) ); // string(16) we demonstrate above inet_* family supports both ipv6 , v4. our next step translate packed result unpacked variable.
// unpacking , packing $_u4 = current( unpack( "a4", inet_pton( $ip4 ) ) ); var_dump( inet_ntop( pack( "a4", $_u4 ) ) ); // string(12) "10.22.99.129" $_u6 = current( unpack( "a16", inet_pton( $ip6 ) ) ); var_dump( inet_ntop( pack( "a16", $_u6 ) ) ); //string(25) "fe80:1:2:3:a:bad:1dea:dad" note : current function returns first index of array. equivelant saying $array[0].
after unpacking , packing, can see achieved same result input. simple proof of concept ensure not losing data.
finally use,
if ($ip <= $high_ip && $low_ip <= $ip) { echo "in range"; } reference: php.net
Comments
Post a Comment