Using find in IP-ranges


I have a table that amongst other things includes two columns,
“start_ip” and “end_ip”. Combined they express a range of IPs, say

Does anyoone know i use find to match an ip to a certain range?

Something along the lines of:

ip = “”
ips = SwedishIp.find_by_something(ip)

Any help is most appreciated. Thanks!

So I’ve converted the IPs to integers using IPAddr, which makes it a
whole lot easier to see if an incoming IP fits a certain range.

The code I’m looking at now is:

@request_ip =
ips = IpRanges.find(:all)
ips.each do |ip|
range = ip.start_ip_integer…ip.end_ip_integer
if range.include?(@request_ip.to_i)
@ip_range = ip
render :text =>

Looks painfully slow to iterate thru every row like that - and I keep it
all in my controller when I assume it should be refactored into my

Any way to speed things up?

Probably the way to speed it up the most is with SQL. Something like
this might work:

IpRanges.find(:all, :conditions => [‘start_ip_integer <= :ip AND
end_ip_integer >= :ip’, {:ip => @request_ip.to_i}])

That would probably be in a class method in your model.

I hope that helps,

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs