Skip to content

Instantly share code, notes, and snippets.

@bsingr
Created November 1, 2011 11:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bsingr/1330349 to your computer and use it in GitHub Desktop.
Save bsingr/1330349 to your computer and use it in GitHub Desktop.
Convert Ipv4 Addresses between Integer and dot-decimal notation using ruby
# How to convert IPv4 addresses between integer <=> dot-decimal notation
INTEGER = 1698212032
DOT_DECIMAL = '192.168.56.101'
# [ 192, 168, 56, 101 ]
DOT_DECIMAL_PARTS = DOT_DECIMAL.split('.').map(&:to_i)
####################################
# integer to dot-decimal
####################################
# 1698212032 => '192.168.56.101'
puts "=== from INTEGER to DOT-DECIMAL ==="
# MANUALLY
number = INTEGER
p1 = (number) & 255 # 192
p2 = (number>>8) & 255 # 168
p3 = (number>>16) & 255 # 56
p4 = (number>>24) & 255 # 101
puts "MANU: #{p1}.#{p2}.#{p3}.#{p4}"
# AUTOMATICALLY
number = INTEGER
result = []
4.times do
# bitwise AND 255 bits
result.push number & 255
# bitwise SHIFT RIGHT 8 bits
number = number >> 8
end
puts "AUTO: #{result.join('.')}"
####################################
# dot-decimal to Integer
####################################
# '192.168.56.101' => 1698212032
puts "=== from DOT-DECIMAL to INTEGER ==="
# MANUALLY
parts = DOT_DECIMAL_PARTS
manually_int = parts[0] +
(parts[1] << 8) +
(parts[2] << 16) +
(parts[3] << 24)
puts "MANU: #{manually_int}"
# AUTOMATICALLY
number = DOT_DECIMAL
parts = DOT_DECIMAL_PARTS.dup
# sum up the integer beginning at 0
result = 4.times.inject(0) do |integer, index|
# take next part
part = parts.shift
# bitwise SHIFT LEFT
add = part << (8 * index)
# add to sum by returning it
integer += add
end
puts "AUTO: #{result}"
@KINGSABRI
Copy link

You are awesome :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment