I wrote a huge rant about stupid people storing IP addresses as a CHAR(15) in the DB. I then gave up and realized stupid people will remain stupid, and intelligent people will learn. Use an INT(4), it’s a huge saving in size and indexing will be fast.
“kris, Im not a stupid person, and want to learn, but how would you recommend doing so?”. Dear reader, I’m not Jesus (yet), but a simple google search will either lead you back to this post, or directly to IPAddr.
1 2 3 4 5 6 | require 'rubygems' require 'ipaddr' ip = IPAddr.new('127.0.0.1') puts "Normal: #{ip.to_s} - Converted: #{ip.to_i}" >> Normal: 127.0.0.1 - Converted: 2130706433 |
What’s even cooler, is the ability to see if an ip belongs to a network.
1 2 3 | network = IPAddr.new("192.168.1.0/24") puts network.include?(IPAddr.new("192.168.1.0")) >> true |
Now, there are many more options, but my goal here is not to teach you IPAddr, but to kick your ass in the proper direction. This way, you won’t write stupid code (Stupid, being completely subjective, for now, until I’m Jesus). G’day.
No related posts.