Skip to content

Instantly share code, notes, and snippets.

@ender672 ender672/gist:166859
Created Aug 12, 2009

Embed
What would you like to do?
module IpStrConvert
# IPv4 Conversion Methods
def ip4_str2bin(s)
s.split('.').map{|str| str.to_i}.pack('C4')
end
def ip4_bin2str(s)
s.unpack('C4').join '.'
end
def ip4_str2int(s)
bin_str = ip4_str2bin s
bin_str.unpack('N')[0]
end
def ip4_int2str(l)
ip4_bin2str([l].pack('N'))
end
# IPv6 Conversion Methods
def ip6_str2bin(s)
a = ip6_str2array s
a.map{|str| [str[0..1], str[2..3]].pack 'H2H2'}.join
end
def ip6_bin2str(s)
s.unpack('H4H4H4H4H4H4H4H4').join ':'
end
def ip6_str2int(s)
bin_str = ip6_str2bin s
parts = bin_str.unpack 'N4'
assemble_double_quad_word parts
end
def ip6_int2str(l)
parts = dissemble_double_quad_word(l, 4)
ip6_bin2str(parts.pack('N4'))
end
private
# take an ipv6 string and return a normalized array containing eight 16-bit
# hex strings
def ip6_str2array(s)
a = s.split ':'
# insert fields substituted by double colons '::'
if a.size < 8
filler = ['0000'] * (8 - a.size)
i = a.index ''
a.insert i, *filler
end
a.map!{|b| b || '0000'}
# pad fields that omit leading zeroes
a.map{|f| f.rjust 4, '0'}
end
def assemble_double_quad_word(parts)
i = parts.size
part_bits = 128 / i
parts.inject(0) do |memo, num|
i -= 1
memo + (num << (i*part_bits))
end
end
def dissemble_double_quad_word(l, num_parts)
parts = []
part_bits = 128 / num_parts
part_mask = 2 ** part_bits - 1
num_parts.times do |i|
shift_bits = (num_parts - 1 - i) * part_bits
parts << ((l >> shift_bits) & part_mask)
end
parts
end
end
include IpStrConvert
s = '2001:db8:85a3::8a2e:370:7334'
#s = 'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'
s = '0::0'
#s = '::'
p 'string 2 bin'
p ip6_str2bin(s)
p ip6_bin2str(ip6_str2bin(s))
p 'string 2 int'
p ip6_str2int(s)
p ip6_int2str(ip6_str2int(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.