Skip to content

Commit

Permalink
Merge pull request #46 from cloudcosmonaut/feat/make-host-count-rfc-c…
Browse files Browse the repository at this point in the history
…ompliant

feat: remember the network and broadcast address
  • Loading branch information
bschaatsbergen committed Sep 12, 2022
2 parents 29ec4c3 + 440e499 commit ddd651c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
19 changes: 13 additions & 6 deletions README.md
Expand Up @@ -33,23 +33,30 @@ This also works with IPv6 addresses, for example:
```
$ cidr contains 2001:db8:1234:1a00::/106 2001:db8:1234:1a00::
true
```
```

### Count distinct host addresses

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

```
$ cidr count 10.0.0.0/16
65536
65534
```

This also works with IPv6 addresses, for example:
Or with large prefixes like point-to-point links:

```
$ cidr count count 172.16.18.0/31
2
```

This also works with very small CIDR ranges, like a point-to-point link:

```
$ cidr count 2001:db8:1234:1a00::/106
4194304
```
```

### CIDR range intersection

Expand All @@ -65,9 +72,9 @@ This also works with IPv6 addresses, for example:
```
$ cidr overlaps 2001:db8:1111:2222:1::/80 2001:db8:1111:2222:1:1::/96
true
```
```

## Contributing

Contributions are highly appreciated and always welcome.
Contributions are highly appreciated and always welcome.
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.
13 changes: 12 additions & 1 deletion pkg/core/core.go
Expand Up @@ -6,7 +6,18 @@ import (

func AddressCount(network *net.IPNet) uint64 {
prefixLen, bits := network.Mask.Size()
return 1 << (uint64(bits) - uint64(prefixLen))

// Check if network is IPv4 or IPv6
if network.Mask != nil {
// Handle edge cases
switch prefixLen {
case 32: return 1
case 31: return 2
}
}

// Remember to subtract the network address and broadcast address
return 1 << (uint64(bits) - uint64(prefixLen)) - 2
}

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

0 comments on commit ddd651c

Please sign in to comment.