I am looking for a php script which will give the total number of hosts for an IPV6 IP address in CIDR format. I know that there are similar posts about this but I have not been able to get any of them to work properly so far. Any help is appreciated.
Asked
Active
Viewed 265 times
-1
-
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it. – Jay Blanchard Jul 18 '17 at 19:04
1 Answers
1
If you have the prefix in CIDR notation then you know the prefix length. The bits usable for hosts are the bits not defined by the prefix. So it's easy to calculate the number:
Take the prefix length (the part after the slash), subtract it from the address length (128), and calculate 2 to the power of the result.

Sander Steffann
- 9,509
- 35
- 40
-
Thanks. That gives me a rough idea, but a single ip (/128) would equate to zero using that formula – AndyC Jul 31 '17 at 01:52
-
-
And it's not a "rough idea", it's the exact answer you were asking for... – Sander Steffann Jul 31 '17 at 09:21
-
-
1Maybe something like: $num = pow(2, 128 - $nm); where $nm is the prefix length would work? – AndyC Jul 31 '17 at 09:55
-
So it turns out that both IPV4 and IPV6 total hosts can be calculated, from a database for example, using: $pos = strpos($ip, "/"); $count = $count + pow(2, 32 - substr($ip, $pos+1)); for IPV4 and: $pos = strpos($ip, "/"); $count6 = $count6 + pow(2, 128 - substr($ip, $pos+1)); where $ip is a CIDR notation IP address. – AndyC Jul 31 '17 at 17:34
-
Shortened to a one-liner: $count = $count + pow(2, 32 - substr($ip, strpos($ip, "/") + 1)); and $count6 = $count6 + pow(2, 128 - substr($ip, strpos($ip, "/") + 1)); – AndyC Jul 31 '17 at 18:49