I have an ipv6 range, but I have no clue how to detect if the $_SERVER['REMOTE_ADDRESS'] is in the ipv6 range? Need help. Thanks
Asked
Active
Viewed 3,844 times
2
-
2Do you mean check if it's in the subnet or check if it's an ipv6 or ipv4 address? – VDP Jan 16 '13 at 14:22
1 Answers
9
The easiest way to check if an address is in a range is to convert the address and the limits of the range to binary and then use normal compare operators:
$first_in_range = inet_pton('2001:db8::');
$last_in_range = inet_pton('2001:db8::ffff:ffff:ffff:ffff');
$address = inet_pton($_SERVER['REMOTE_ADDR']);
if ((strlen($address) == strlen($first_in_range))
&& ($address >= $first_in_range && $address <= $last_in_range)) {
// In range
} else {
// Not in range
}

Sander Steffann
- 9,509
- 35
- 40
-
Oh, I forgot that the output of `inet_pton()` is treated as a string. When comparing them the length of the string must also be checked in order to prevent an IPv4 address to match the first part of an IPv6 address. I'll fix the example. – Sander Steffann Jan 17 '13 at 09:00