-1

I am trying to do a PHP function which retrieves range boundaries of an IPv6 when we gives it an IPv6 and its CIDR.

Example -> Parameter :

2001:0db8:85a3:0000:0000:8a2e:0370:7334/100

Example -> Expected result :

[
    [0] => "2001:db8:85a3::8a2e:0:0",
    [1] => "2001:db8:85a3::8a2e:fff:ffff"
]

I found it easily for an IPv4 but not for an IPv6. I tried most of the things found in Google, like this : https://localcoder.org/calculate-ip-range-using-php-and-cidr but got the following error when I tried with my CIDR. Warning: hex2bin(): Hexadecimal input string must have an even length.

I also tried this function :

$range = [];

$range[0] = $this->long2ip_v6(($this->ip2long_v6($ip)) & ((-1 << (128 - (int)$cidr))));
$range[1] = $this->long2ip_v6(($this->ip2long_v6($range[0])) + pow(2, (128 - (int)$cidr)) - 1);

return $range;

inspired for the one for IPv4, working with this functions to convert IPv6 : Php convert ipv6 to number

But I got the following error. gmp_init(): Argument #1 ($num) must be of type GMP|string|int, float given

So now I don't know what to do. How to retrieve boundaries of the range where a given IPv6 is inside please ?

Edit : I know my question is close to this one : Calculate an IPv6 range from a CIDR prefix? But this does not answers to me : in this link, we send to the function the first IP of the range (with its cidr). My case is not this one, because I send an IP in the range. I do not know the first IP of the range when I am "asking" the function. It can be an IP which is anywhere in the range : it can be start, middle, end, etc, like in the example where it is 2001:0db8:85a3:0000:0000:8a2e:0370:7334.

Martin S.
  • 21
  • 6
  • You did not read all the answers. [This answer](https://stackoverflow.com/a/61883041/3745413) to the linked question corrects your objection. – Ron Maupin May 06 '22 at 21:10
  • Oh, thanks @RonMaupin. I thought I had read everything of this question, but I hadn't done it right. So thank you for your answer ! – Martin S. May 08 '22 at 17:43

0 Answers0