Count IP addresses - ruby

I stored the following IPs in an array:
10.2.3.1
10.2.3.5
10.2.3.10 - 10.2.3.15
I'm trying to count the total number of IP addresses. The total number of IP addresses should be 8. When I iterate through the array, I get a total of three counts. I need a way to count the third item:
10.2.3.10 - 10.2.3.15
Are there any IP address counters?

If you need to convert an IP to a range, you'll need a function that converts an IPv4 value to an integer, then do math on those:
require 'ipaddr'
def ip(string)
IPAddr.new(string).to_i
end
def parse_ip(string)
string.split(/\s+\-\s+/).collect { |v| ip(v) }
end
def ip_range(string)
ips = parse_ip(string)
ips.last - ips.first + 1
end
ip_range("10.2.3.10 - 10.2.3.15")
# => 6
That should do it.

It makes perfect sense to use the IPAddr class, as #tadman did, but it should be noted that the methods in that class are not doing anything very special. #tadman's answer works just fine if his method ip (the only one to use an IPAddr method) is replaced with:
def ip(str)
str.split('.').map { |s| s.to_i.to_s(2).rjust(8,'0') }.join.to_i(2)
end
Let's compare:
require 'ipaddr'
def tadip(string)
IPAddr.new(string).to_i
end
str = "10.2.3.10"
tadip str #=> 167904010
ip str #=> 167904010
str = "255.255.255.255"
tadip str #=> 4294967295
ip str #=> 4294967295
str = "172.0.254.1"
tadip str #=> 2885746177
ip str #=> 2885746177
In fact, ip, unlike IPAddr::new works for IPv6 (32**2 bits) as well as IPv4 (32 bits) IP's (-:
str = "172.0.254.1.22.33.44.55"
tadip str #=> IPAddr::InvalidAddressError: invalid address
ip str #=> 12394185455143300151

to count interval between two IP without ipaddr library :)
int32start = "10.0.0.0".split(".").map(&:to_i).pack('CCCC').unpack('N')[0]
int32ending = "10.0.0.50".split(".").map(&:to_i).pack('CCCC').unpack('N')[0]
puts int32ending - int32start #50

Related

Ruby: Convert CIDR to Netmask

Given a network definition like 192.168.1.0/24, I'd like to convert the /24 CIDR to a four digit netmask, in this case 255.255.255.0.
No extra gems should be used.
The actual method here is pretty simple:
def mask(n)
[ ((1 << 32) - 1) << (32 - n) ].pack('N').bytes.join('.')
end
Where that can give you results like:
mask(24)
# => "255.255.255.0"
mask(16)
# => "255.255.0.0"
mask(22)
# => "255.255.252.0"
Ruby's IPAddr does not appear to expose this functionality. However, it contains a private instance variable called #mask_addr that contains the integer value of the desired mask.
It can be represented as a four digit submask by converting it back to another IPAddr instance:
require "ipaddr"
net = IPAddr.new("192.168.1.0/24")
subnet = IPAddr.new(net.instance_variable_get(:#mask_addr), Socket::AF_INET).to_s
# => "255.255.255.0"

Need help matching IP subnet with ruby regex

I am trying to match first two octets of an IP to determine network subnet.
IP start with 10.43 or 10.44 or 10.46 but not 10.45, tried to match with this expression 10.4{3|4|6} but it matches only 10.44 and 10.46
Any guess why not matching 10.43
While a regex will work (#Stefan has already provided one) and I have no idea about your implementation the IPAddr standard library may interest you e.g.
acceptable_sub_nets = ["10.43.0.0","10.44.0.0","10.46.0.0"]
my_list_of_ips.select do |ip|
acceptable_sub_nets.include?(IPAddr.new(ip).mask(16).to_s)
end
For example
IPAddr.new("10.43.22.19").mask(16).to_s
#=> "10.43.0.0"
IPAddr.new("192.168.0.1").mask(16).to_s
#=> "192.168.0.0"
Additionally you could do something like
acceptable_sub_nets = ["10.43.0.0","10.44.0.0","10.46.0.0"].map do |subnet|
IPAddr.new(subnet).mask(16).to_range
end
my_list_of_ips.select do |ip|
acceptable_sub_nets.any? {|range| range.cover?(ip) }
end
Example
subnet_range = IPAddr.new("10.43.0.0").mask(16).to_range
subnet_range.cover?("10.43.22.19")
#=> true
subnet_range.cover?("192.168.0.1")
#=> false
Update (Thank you #JordanRunning)
The second option can be simplified to
acceptable_sub_nets = [
#including the mask range
IPAddr.new("10.43.0.0/16"),
IPAddr.new("10.44.0.0/16"),
IPAddr.new("10.46.0.0/16")]
my_list_of_ips.select do |ip|
acceptable_sub_nets.any? {|range| range.include?(ip) }
end
This does not require conversion to a Range but rather leverages IPAddr#include? directly.

How to increment the last octet in an IP address

How to write a ruby helper function which will increment from 222.164.153.58 to 222.164.153.59 or increment the 3rd octet properly if it hits the max on the 4th octet.
Use IPAddr#succ.
require "ipaddr"
addr = IPAddr.new "222.164.153.58"
addr.succ
#=> #<IPAddr: IPv4:222.164.153.59/255.255.255.255>
addr = IPAddr.new "192.168.2.255"
addr.succ
#=> #<IPAddr: IPv4:192.168.3.0/255.255.255.255>
ipaddrobjects have a succ method
require "ipaddr"
ip = IPAddr.new("222.164.153.58")
5.times{puts ip; ip = ip.succ}
#222.164.153.58
#222.164.153.59
#222.164.153.60
#222.164.153.61
#222.164.153.62
If you need to increment by more than one, succ isn't super helpful because you have to do it in a loop. Say you want to calculate the upper and lower of 3000 addresses:
require 'ipaddr'
lower = IPAddr.new('10.0.0.0')
upper = IPAddr.new(lower.to_i + 3000, Socket::AF_INET)
Then you can iterate them like so:
for ip in lower..upper
# Do something with ip
end

Ruby: How to convert IP range to array of IP's

Is there any easy way to convert IP range to array of IPs?
def convertIPrange (start_ip, end_ip)
#output: array of ips end
end
e.g. input
('192.168.1.105', '192.168.1.108')
output
['192.168.1.105','192.158.1.106','192.158.1.107','192.158.1.108']
Use the Ruby standard library IPAddr
# I would suggest naming your function using underscore rather than camelcase
# because of Ruby naming conventions
#
require 'ipaddr'
def convert_ip_range(start_ip, end_ip)
start_ip = IPAddr.new(start_ip)
end_ip = IPAddr.new(end_ip)
# map to_s if you like, you can also call to_a,
# IPAddrs have some neat functions regarding IPs,
# be sure to check them out
#
(start_ip..end_ip).map(&:to_s)
end
def convertIPrange first, last
first, last = [first, last]
.map{|s| s.split(".").inject(0){|i, s| i = 256 * i + s.to_i}}
(first..last).map do |q|
a = []
(q, r = q.divmod(256)) && a.unshift(r) until q.zero?
a.join(".")
end
end
convertIPrange('192.168.1.105', '192.168.1.108')
# => ["192.168.1.105", "192.168.1.106", "192.168.1.107", "192.168.1.108"]
convertIPrange('192.255.255.254', '193.0.0.1')
# => ["192.255.255.254", "192.255.255.255", "193.0.0.0", "193.0.0.1"]

Netmask to CIDR in ruby

I've been using the ip-address gem and it doesn't seem to have the ability to convert from a netmask of the form
255.255.255.0
into the CIDR form
/24
Does anyone have an ideas how to quickly convert the former to the latter ?
Here is the quick and dirty way
require 'ipaddr'
puts IPAddr.new("255.255.255.0").to_i.to_s(2).count("1")
There should be proper function for that, I couldn't find that, so I just count "1"
If you're going to be using the function in a number of places and don't mind monkeypatching, this could help:
IPAddr.class_eval
def to_cidr
"/" + self.to_i.to_s(2).count("1")
end
end
Then you get
IPAddr.new('255.255.255.0').to_cidr
# => "/24"
Just as a FYI, and to keep the info easily accessible for those who are searching...
Here's a simple way to convert from CIDR to netmask format:
def cidr_to_netmask(cidr)
IPAddr.new('255.255.255.255').mask(cidr).to_s
end
For instance:
cidr_to_netmask(24) #=> "255.255.255.0"
cidr_to_netmask(32) #=> "255.255.255.255"
cidr_to_netmask(16) #=> "255.255.0.0"
cidr_to_netmask(22) #=> "255.255.252.0"
Here's a more mathematical approach, avoiding strings at all costs:
def cidr_mask
Integer(32-Math.log2((IPAddr.new(mask,Socket::AF_INET).to_i^0xffffffff)+1))
end
with "mask" being a string like 255.255.255.0. You can modify it and change the first argument to just "mask" if "mask" is already an integer representation of an IP address.
So for example, if mask was "255.255.255.0", IPAddr.new(mask,Socket::AF_INET).to_i would become 0xffffff00, which is then xor'd with 0xffffffff, which equals 255.
We add 1 to that to make it a complete range of 256 hosts, then find the log base 2 of 256, which equals 8 (the bits used for the host address), then subtract that 8 from 32, which equals 24 (the bits used for the network address).
We then cast to integer because Math.log2 returns a float.
Quick and dirty conversion:
"255.255.255.0".split(".").map { |e| e.to_i.to_s(2).rjust(8, "0") }.join.count("1").split(".")
=> I split mask in an Array
.map { |e| e.to_i.to_s(2).rjust(8, "0") }
=> For each element in Array:
.to_i
=> Convert into integer
.to_s(2)
=> Convert integer into binary
.rjust(8, "0")
=> Add padding
=> Map return a Array with same cardinality
.join
=> Convert Array into a full string
.count("1")
=> Count "1" characters => Give CIDR mask
def mask_2_ciddr mask
"/" + mask.split(".").map { |e| e.to_i.to_s(2).rjust(8, "0") }.join.count("1").to_s
end
mask_2_ciddr "255.255.255.0"
=> "/24"
mask_2_ciddr "255.255.255.128"
=> "/25"
If you don't need to use ip-address gem, you can do this with the netaddr gem
require 'netaddr'
def to_cidr_mask(dotted_mask)
NetAddr::CIDR.create('0.0.0.0/'+dotted_mask).netmask
end
to_cidr_mask("255.224.0.0") # => "/11"
require 'ipaddr'
def serialize_ipaddr(address)
mask = address.instance_variable_get(:#mask_addr).to_s(2).count('1')
"#{address}/#{mask}"
end
serialize_ipaddr(IPAddr.new('192.168.0.1/24')) # => "192.168.0.0/24"
The code achieves the masking by accessing private instance variable *#mask_addr) of IPAddr instance (address, passed into serialize_ipaddr). This is not recommended way (as the instance variables are not part of the classes public API but here it's better than parsing the string from #inspect in my opinion.
So the process is as follows:
Get the instance variable #mask_addr that represents netmask
Get its binary representation e.g. 255.255.255.0 -> 4294967040 -> 11111111111111111111111100000000
Count the 1-s in the base-2 number to get CIDR mask (24)
Make up a string consisting the address & mask
EDIT: Added explanation to the implementation as requested by NathanOliver
Here is a way to do it without the IPAddr gem
(('1'*cidr)+('0'*(32-cidr))).scan(/.{8}/m).map{|e|e.to_i(2)}.join('.')

Resources