This question already has answers here:
How do I check whether a value in a string is an IP address
(13 answers)
Closed 8 years ago.
I want to verify whether a given string is valid IPv4 address or not in ruby.
I tried as follows but what is does is matches values greater than 255 as well.
How to limit each block's range from 0-255
str="255.255.255.256"
if str=~ /\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b/
puts true
else
puts false
end
You have the IPAddr class in Ruby. You do not need to validate it agains a regex, just create a new object and catch the exception when it fails:
require 'ipaddr'
ip = IPAddr.new "127.0.0.1"
# => #<IPAddr: IPv4:127.0.0.1/255.255.255.255>
ip = IPAddr.new "127.0.0.a"
# => IPAddr::InvalidAddressError: invalid address
block = /\d{,2}|1\d{2}|2[0-4]\d|25[0-5]/
re = /\A#{block}\.#{block}\.#{block}\.#{block}\z/
re =~ "255.255.255.255" # => 0
re =~ "255.255.255.256" # => nil
You'd better to use ruby core class IPAddress
you could do it this way:
require "ipaddress"
IPAddress.valid? "192.128.0.12"
#=> true
IPAddress.valid? "192.128.0.260"
#=> false
you could find more here How do I check whether a value in a string is an IP address
This is a way that reads pretty easily:
str.count('.')==3 && str.split('.').all? {|s| s[/^\d{3}$/] && s.to_i < 256}
Related
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.
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
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"]
The script has to verify if one predefined IP is present in a big array of IPs. Currently I code that function like this (saying that "ips" is my array of IP and "ip" is the predefined ip)
ips.each do |existsip|
if ip == existsip
puts "ip exists"
return 1
end
end
puts "ip doesn't exist"
return nil
Is there a faster way to do the same thing?
Edit : I might have wrongly expressed myself. I can do array.include? but what I'd like to know is : Is array.include? the method that will give me the fastest result?
You can use Set. It is implemented on top of Hash and will be faster for big datasets - O(1).
require 'set'
s = Set.new ['1.1.1.1', '1.2.3.4']
# => #<Set: {"1.1.1.1", "1.2.3.4"}>
s.include? '1.1.1.1'
# => true
You could use the Array#include method to return you a true/false.
http://ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F
if ips.include?(ip) #=> true
puts 'ip exists'
else
puts 'ip doesn\'t exist'
end
A faster way would be:
if ips.include?(ip)
puts "ip exists"
return 1
else
puts "ip doesn't exist"
return nil
end
ips = ['10.10.10.10','10.10.10.11','10.10.10.12']
ip = '10.10.10.10'
ips.include?(ip) => true
ip = '10.10.10.13'
ips.include?(ip) => false
check Documentaion here
have you tried the Array#include? function?
http://ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F
You can see from the source it does almost exactly the same thing, except natively.
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('.')