Working with IP address information using Ruby

June 2, 2016

I recently needed to create an IP address range in array format, and came across a nice Ruby Class “ipaddr” for working with IP address information. My goal was to white list an IP by cross referencing it with the IP address range.

Here is a standalone example of converting the IP Range into an array.

#!/usr/bin/env ruby

require 'ipaddr'

def ip_range(first, last)
  first = IPAddr.new(first)
  last  = IPAddr.new(last)
  (first..last).map(&:to_s)
end

range_calc = ip_range("172.30.20.0", "172.30.20.255")

puts range_calc.to_a


Here is an example in Sinatra of using this method to check against

require 'ipaddr'

get '/blah/blah/blah' do

def ip_range(first, last)
  first = IPAddr.new(first)
  last  = IPAddr.new(last)
  (first..last).map(&:to_s)
end

range_calc = ip_range("172.30.20.0", "172.30.20.255")

$WHITE_LIST_HOSTS = ["127.0.0.1","173.255.251.204","54.223.213.220"] + range_calc.to_a

request_ip = @env['HTTP_X_REAL_IP']
  if
    !$WHITE_LIST_HOSTS.include? request_ip

  return "Not Authorized"

  else
    Do work here...
  end
end


Here is another standalone example variation using a method of ip-addr, if the requesting ip is in the range it will return true.

#!/usr/bin/env ruby

require 'ipaddr'

first = IPAddr.new("172.30.20.0/24")

requesting_ip = IPAddr.new("172.30.20.200")

puts first.include?(requesting_ip)


Hope this is helpful. The Class ‘ipaddr‘ has other useful methods you should check out.

Comments are closed.