CIDR
CIDR is a simple utility to generate the IPv4 addresses in a CIDR range. It could also be used to check the membership of an IP v4 address in a CIDR range.
Using as a library
In order to start, go get this repository:
go get github.com/adedayo/cidr
Example
In your code simply import as usual and enjoy:
package main
import "github.com/adedayo/cidr"
func main() {
ips := cidr.Expand("192.168.2.5/30")
for _, ip := range ips {
println(ip)
}
}
This should print the set of IPs described by the CIDR range 192.168.2.5/30:
192.168.2.4
192.168.2.5
192.168.2.6
192.168.2.7
CIDR is also available as a command-line tool.
Installation
Prebuilt binaries may be found for your operating system here: https://github.com/adedayo/cidr/releases
For macOS X, you could install via brew as follows:
brew tap adedayo/tap
brew install cidr
Generating IPs in a CIDR range
cidr 192.168.2.5/30 10.11.12.13/31
This should generate a simply formatted output:
192.168.2.5/30: 192.168.2.4 192.168.2.5 192.168.2.6 192.168.2.7
10.11.12.13/31: 10.11.12.12 10.11.12.13
For a JSON-formatted result, use the JSON -j
or --json
flag:
cidr --json 192.168.2.5/30 10.11.12.13/31
This should produce:
{
"192.168.2.5/30": ["192.168.2.4", "192.168.2.5", "192.168.2.6", "192.168.2.7"],
"10.11.12.13/31": ["10.11.12.12", "10.11.12.13"]
}
Checking CIDR range membership
The structure of the checking command is as follows
cidr [flag] check <space separated list of CIDR ranges> <delimiter> <space-separated list of IP addresses to check>
The delimiter can be any of contains
or simply ,
Examples
To check the membership of the IP addresses 192.168.10.3 and 192.168.10.9 in the CIDR ranges 192.168.10.1/30 and 192.168.10.1/28 run
cidr check 192.168.10.1/30 192.168.10.1/28 contains 192.168.10.3 192.168.10.9
The result is
192.168.10.1/30: 192.168.10.3,true 192.168.10.9,false
192.168.10.1/28: 192.168.10.3,true 192.168.10.9,true
For a JSON output the above is equivalent to
cidr --json check 192.168.10.1/30 192.168.10.1/28 , 192.168.10.3 192.168.10.9
This produces
{
"192.168.10.1/30": [{"ip":"192.168.10.3","belongs":true},{"ip":"192.168.10.9","belongs":false}],
"192.168.10.1/28": [{"ip":"192.168.10.3","belongs":true},{"ip":"192.168.10.9","belongs":true}]
}
License
BSD 3-Clause License