Created
March 17, 2012 19:06
-
-
Save simon2k/2064278 to your computer and use it in GitHub Desktop.
IpCalculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ip < Array | |
def initialize(arg) | |
case arg | |
when Array # array with octets | |
concat(arg) | |
when /(\d{1,3}\.){3}\d{1,3}/ # string with decimal address - splitted by dots | |
concat(arg.split('.')).map!(&:to_i) | |
when /\d{1,32}/ # string with binary address - not splitted by dots | |
concat(arg.scan(/\d{1,8}/).map { |oct| oct.to_i(2) }) | |
else | |
raise 'Passed argument is not valid!' | |
end | |
end | |
def to_binary | |
map.each.inject('') do |octets, part| | |
binary = part.to_s(2) | |
octets += binary.insert(0, '0' * (8 - binary.size)) # complemented with '0' at 0 position if octet has not 8 digits | |
end | |
end | |
def to_s | |
join('.') | |
end | |
end | |
class Mask < Ip | |
def initialize(arg) | |
if arg.kind_of?(Integer) | |
binary_mask = '1' * arg + '0' * (32 - arg) # create binary address | |
super(binary_mask) | |
else | |
super(arg) | |
end | |
raise 'Mask is not valid!' if to_binary[/1{1,32}0{1,32}/].size < 32 | |
end | |
end | |
class IpCalculator | |
attr_reader :ip, :mask | |
def initialize(ip, mask) | |
@ip = Ip.new(ip) | |
@mask = Mask.new(mask) | |
end | |
def host | |
host = [] | |
ip.each_with_index do |el, i| | |
host[i] = el & mask[i] | |
end | |
Ip.new(host) | |
end | |
def broadcast | |
binary_host = host.to_binary | |
number_of_zeros = mask.to_binary.reverse.scan(/./).index('1') | |
binary_host[-number_of_zeros..-1] = '1' * number_of_zeros # change from 0 to 1 | |
Ip.new(binary_host) | |
end | |
end | |
calc = IpCalculator.new('126.0.0.1', '255.255.248.0') | |
puts "ip: #{calc.ip}" | |
puts "mask: #{calc.mask}" | |
puts 'calculating..' | |
puts "host: #{calc.host}" | |
puts "broadcast: #{calc.broadcast}" | |
puts '---' | |
ip = Ip.new('126.0.0.1') | |
mask = Mask.new('255.255.248.0') | |
calc = IpCalculator.new(ip, mask) | |
puts "ip: #{calc.ip}" | |
puts "mask: #{calc.mask}" | |
puts 'calculating..' | |
puts "host: #{calc.host}" | |
puts "broadcast: #{calc.broadcast}" | |
puts '---' | |
calc = IpCalculator.new(ip, 21) | |
puts "ip: #{calc.ip}" | |
puts "mask: #{calc.mask}" | |
puts 'calculating..' | |
puts "host: #{calc.host}" | |
puts "broadcast: #{calc.broadcast}" | |
puts '---' | |
puts 'Mask validator' | |
begin | |
Mask.new '123.123.123.0' | |
rescue RuntimeError | |
puts 'Huh! your mask is not valid ;-(' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment