Skip to content

Instantly share code, notes, and snippets.

@rainly
Forked from IceskYsl/ip2int
Created March 23, 2011 09:51
Show Gist options
  • Select an option

  • Save rainly/882867 to your computer and use it in GitHub Desktop.

Select an option

Save rainly/882867 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment