SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

IP to integer (ip2int, int2ip)

Posted on May 25th, 2007 by Alex Gorbatchev. In Ruby. No comments yet...

When storing IP in a database, it’s much better to store them as integers rather than VARCHAR(15). Here’s a handy function to convert an IP string to integer and back.

# Converts an IP string to integer
def ip2int(ip)
  return 0 unless ip =~ /d{1,3}.d{1,3}.d{1,3}.d{1,3}/

  v = ip.split('.').collect { |i| i.to_i }
  return (v[0] << 24) | (v[1] << 16) | (v[2] << 8 ) | (v[3]);
end

# Converts an integer to IP string... could be prettier
def int2ip(int)
  tmp = int.to_i
  parts = []

  3.times do |i|
    tmp = tmp / 256.0
    parts << (256 * (tmp - tmp.to_i)).to_i
  end

  parts << tmp.to_i
  parts.reverse.join('.')
end
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet, be the first one!

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr