Introduction

The NetSpace gem exists to provide a very basic subnet calculation functionality. I found that I used subnet membership calculations often in my scripts, and grew tired of copying and pasting this code around all the time. Perhaps it may be useful to you. You can install NetSpace using the following command:

# gem install netspace

A basic utility is included as an executable script with this gem. It functions as a basic 'grep' for substrings matching IP addresses in a provided list of subnets. The basic command doc is as follows:

 usage: netspace <subnets>

     File containing CIDR notated subnets

 Matches STDIN for IPs contained in the subnets provided in the
 specified input file.  I.e., acts as a CIDR-aware IP grep.

Code Examples

The following example shows how to specify a subnet and test IP membership:

$ pry
[1] pry(main)> require 'netspace'
=> true
[2] pry(main)> s = NetSpace::Subnet.new("192.168.1.32", 28)
=> #<NetSpace::Subnet:0x007ff39e0ea210
 @bits=28,
 @ip="192.168.1.32",
 @ip32=3232235808,
 @mask="255.255.255.240",
 @mask32=-16>
[3] pry(main)> s.in? "192.168.1.1"
=> false
[4] pry(main)> s.in? "192.168.1.34"
=> true
[5] pry(main)>

You can also get a listing of all IPs in a subnet as follows:

$ pry
[1] pry(main)> require 'netspace'
=> true
[2] pry(main)> NetSpace::Subnet.new("192.168.7.16", 29).ips
=> ["192.168.7.16",
 "192.168.7.17",
 "192.168.7.18",
 "192.168.7.19",
 "192.168.7.20",
 "192.168.7.21",
 "192.168.7.22",
 "192.168.7.23"]
  [3] pry(main)> 

Finally, you can load blocks of subnets from files or parse them from strings using some functions provided in the NetSpace module:

NetSpace::load("/path/to/cidr.txt")
NetSpace::parse(File.read("/path/to/cidr.txt"))

These assume that the contents of the subnet specification file includes one subnet per line.