# Using find in IP-ranges

**URL:** <https://www.ruby-forum.com/t/using-find-in-ip-ranges/133288>\
**Category:** Rails\
**Created:** [March 29, 2008, 7:30pm UTC](https://www.ruby-forum.com/t/using-find-in-ip-ranges/133288 "2008-03-29T19:30:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gustav](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/919ad9/32.png) [@gustav](https://www.ruby-forum.com/u/gustav)\
**Post date:** [March 29, 2008, 7:30pm UTC](https://www.ruby-forum.com/t/using-find-in-ip-ranges/133288/1 "2008-03-29T19:30:38Z")

</div>

Hi!

I have a table that amongst other things includes two columns,  
“start\_ip” and “end\_ip”. Combined they express a range of IPs, say  
127.0.0.0-127.0.0.100.

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

Something along the lines of:

ip = “127.0.0.3”  
ips = SwedishIp.find\_by\_something(ip)

Any help is most appreciated. Thanks!

---

<div class="post-metadata">

**Author:** ![gustav](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/919ad9/32.png) [@gustav](https://www.ruby-forum.com/u/gustav)\
**Post date:** [March 30, 2008, 3:33am UTC](https://www.ruby-forum.com/t/using-find-in-ip-ranges/133288/2 "2008-03-30T03:33:16Z")

</div>

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 = IPAddr.new(request.remote\_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  
end  
end  
render :text =\> @ip\_range.group

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  
IpRange-model?

Any way to speed things up?

---

<div class="post-metadata">

**Author:** ![gustav](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/919ad9/32.png) [@gustav](https://www.ruby-forum.com/u/gustav)\
**Post date:** [April 3, 2008, 10:12am UTC](https://www.ruby-forum.com/t/using-find-in-ip-ranges/133288/3 "2008-04-03T10:12:20Z")

</div>

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,  
Paul
