Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

ip

ipv6

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

like image 474
Lj Pearson Avatar asked Oct 24 '25 11:10

Lj Pearson


1 Answers

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
}
like image 89
Sander Steffann Avatar answered Oct 26 '25 00:10

Sander Steffann