Skip to content

Commit ddd651c

Browse files
Merge pull request #46 from cloudcosmonaut/feat/make-host-count-rfc-compliant
feat: remember the network and broadcast address
2 parents 29ec4c3 + 440e499 commit ddd651c

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

README.md

+13-6
Original file line numberDiff line numberDiff line change
@@ -33,23 +33,30 @@ This also works with IPv6 addresses, for example:
3333
```
3434
$ cidr contains 2001:db8:1234:1a00::/106 2001:db8:1234:1a00::
3535
true
36-
```
36+
```
3737

3838
### Count distinct host addresses
3939

4040
To get all distinct host addresses part of a given CIDR range:
4141

4242
```
4343
$ cidr count 10.0.0.0/16
44-
65536
44+
65534
4545
```
4646

47-
This also works with IPv6 addresses, for example:
47+
Or with large prefixes like point-to-point links:
48+
49+
```
50+
$ cidr count count 172.16.18.0/31
51+
2
52+
```
53+
54+
This also works with very small CIDR ranges, like a point-to-point link:
4855

4956
```
5057
$ cidr count 2001:db8:1234:1a00::/106
5158
4194304
52-
```
59+
```
5360

5461
### CIDR range intersection
5562

@@ -65,9 +72,9 @@ This also works with IPv6 addresses, for example:
6572
```
6673
$ cidr overlaps 2001:db8:1111:2222:1::/80 2001:db8:1111:2222:1:1::/96
6774
true
68-
```
75+
```
6976

7077
## Contributing
7178

72-
Contributions are highly appreciated and always welcome.
79+
Contributions are highly appreciated and always welcome.
7380
Have a look through existing [Issues](https://github.com/bschaatsbergen/cidr/issues) and [Pull Requests](https://github.com/bschaatsbergen/cidr/pulls) that you could help with.

pkg/core/core.go

+12-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,18 @@ import (
66

77
func AddressCount(network *net.IPNet) uint64 {
88
prefixLen, bits := network.Mask.Size()
9-
return 1 << (uint64(bits) - uint64(prefixLen))
9+
10+
// Check if network is IPv4 or IPv6
11+
if network.Mask != nil {
12+
// Handle edge cases
13+
switch prefixLen {
14+
case 32: return 1
15+
case 31: return 2
16+
}
17+
}
18+
19+
// Remember to subtract the network address and broadcast address
20+
return 1 << (uint64(bits) - uint64(prefixLen)) - 2
1021
}
1122

1223
func ParseCIDR(network string) (*net.IPNet, error) {

0 commit comments

Comments
 (0)