Range Comparison (including IPv6 support)
In PHP 5.1.0, inet_pton and inet_pton following two functions were introduced. Their goal is to translate human readable IP addresses into their packed in_addr representation. Since the result is not pure binary, we need to use the unpack function to apply bitwise operators.
Both features support IPv6 as well as IPv4. The only difference is how you unpack the address from the results. With IPv6, you unzip the contents using A16, and with IPv4 you unzip the A4.
To put the previous one in perspective, here is a small example of the output to help 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 that the inet_ * family supports both IPv6 and v4. The next step is to translate the packaged result into an unpacked variable.
// Unpacking and 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. The current function returns the first index of the array. This is equivalent to the statement $ array [0].
After unpacking and packaging, we see that we have achieved the same result as the entrance. This is a simple proof of concept to ensure that we do not lose any data.
Finally use
if ($ip <= $high_ip && $low_ip <= $ip) { echo "in range"; }
Link: php.net
Sazzad Hissain Khan Dec 28 '15 at 20:30 2015-12-28 20:30
source share