Lj Pearson
Lj Pearson

Reputation: 115

PHP: How to detect IPv6 is on an IPV6 Range?

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

Upvotes: 4

Views: 4365

Answers (1)

Sander Steffann
Sander Steffann

Reputation: 9978

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
}

Upvotes: 11

Related Questions