Ruby


Yesterday, a friend of mine asked me if I’d recommend Ruby programming language. I’ve said that, even if I had never tried it, it is said to be very reliable. Nevertheless, I’ve decided to try it, just by curiosity. So I’ve gone to the Ruby language website, and there, I’ve found some code, a hello word example:

# The Greeter class
class Greeter
  def initialize(name)
    @name = name.capitalize
  end
 
  def salute
    puts "Hello #{@name}!"
  end
end
 
# Create a new object
g = Greeter.new("world")
 
# Output "Hello World!"
g.salute

I tried it, and until today, forgotten it. But, today, I wanted to do a script to generate all IP addresses in an IP block. I first thought to do it in python, a language I’m more familiar with, but, still driven by curiosity, I’ve wondered if I could do it in Ruby. And that’s what it gave:

#!/usr/bin/env ruby
# The NetMask class
class NetMask
	@mask
	@baseIP
	def initialize()
		@mask = 0
		@baseIP = 0
	end
	def parseFromString(str)
		array = str.split(".")
		if array.length != 4
			array = str.split("-")
		end
		if array.length == 4
			@mask = array[0].to_i + array[1].to_i * 256 + array[2].to_i * 65536 + array[3].to_i * 16777216
		end
	end
	def setFromInt(value)
		@mask = ('1' * value + '0' * (32 - value)).to_i(2)
	end
	def parseBaseIPFromString(str)
		array = str.split(".")
		if array.length != 4
			array = str.split("-")
		end
		if array.length == 4
			@baseIP = array[0].to_i * 16777216 + array[1].to_i * 65536 + array[2].to_i * 256 + array[3].to_i
		end
	end
	def formatIntToIP(int)
		return (int/16777216).to_s+ "." + ((int/65536)%256).to_s + "." + ((int/256)%256).to_s + "." + (int%256).to_s
	end
	def getMask()
		return formatIntToIP(@mask)
	end
	def getBaseIP()
		return formatIntToIP(@baseIP)
	end
	def generateIPList()
		array = []
		for i in (@baseIP & @mask) .. ((@baseIP & @mask) | ((2**32)-1)-@mask) do
			array.push(formatIntToIP(i))
		end
		return array
	end
end
 
mask = NetMask.new()
args = ARGV[0].split("/")
if args.length == 2
	mask.parseBaseIPFromString(args[0])
	mask.setFromInt(args[1].to_i)
else
	mask.parseBaseIPFromString(ARGV[0])
	mask.setFromInt(ARGV[1].to_i)
end
puts mask.generateIPList()

Just for information, the help is here.

  1. No comments yet.
(will not be published)