mirror of
https://github.com/faucetsdn/ryu.git
synced 2026-05-08 22:06:10 +02:00
lib/ip: Add method to convert the format of Ipv4 or Ipv6
Signed-off-by: Shinpei Muraoka <shinpei.muraoka@gmail.com> Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
This commit is contained in:
parent
df1434a9bb
commit
ec1749beca
@ -64,3 +64,34 @@ def ipv6_to_str(ip):
|
||||
:return: IPv6 address string
|
||||
"""
|
||||
return addrconv.ipv6.bin_to_text(ip)
|
||||
|
||||
|
||||
def text_to_bin(ip):
|
||||
"""
|
||||
Converts human readable IPv4 or IPv6 string to binary representation.
|
||||
:param str ip: IPv4 or IPv6 address string
|
||||
:return: binary representation of IPv4 or IPv6 address
|
||||
"""
|
||||
|
||||
if ':' not in ip:
|
||||
data = addrconv.ipv4.text_to_bin(ip)
|
||||
else:
|
||||
data = addrconv.ipv6.text_to_bin(ip)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def bin_to_text(ip):
|
||||
"""
|
||||
Converts binary representation to human readable IPv4 or IPv6 string.
|
||||
:param ip: binary representation of IPv4 or IPv6 address
|
||||
:return: IPv4 or IPv6 address string
|
||||
"""
|
||||
if len(ip) == 4:
|
||||
data = addrconv.ipv4.bin_to_text(ip)
|
||||
elif len(ip) == 16:
|
||||
data = addrconv.ipv6.bin_to_text(ip)
|
||||
else:
|
||||
raise struct.error('Invalid ip address length: %s' % len(ip))
|
||||
|
||||
return data
|
||||
|
||||
@ -86,3 +86,29 @@ class Test_ip(unittest.TestCase):
|
||||
res = ip.ipv6_to_str(ipv6_bin)
|
||||
print('%s %s' % (val, res))
|
||||
eq_(val, res)
|
||||
|
||||
def test_text_to_bin_from_ipv4_text(self):
|
||||
ipv4_str = '10.28.197.1'
|
||||
val = struct.pack('!4B', 10, 28, 197, 1)
|
||||
res = ip.text_to_bin(ipv4_str)
|
||||
eq_(val, res)
|
||||
|
||||
def test_text_to_bin_from_ipv6_text(self):
|
||||
ipv6_str = '2013:da8:215:8f2:aa20:66ff:fe4c:9c3c'
|
||||
val = struct.pack('!8H', 0x2013, 0xda8, 0x215, 0x8f2, 0xaa20,
|
||||
0x66ff, 0xfe4c, 0x9c3c)
|
||||
res = ip.text_to_bin(ipv6_str)
|
||||
eq_(val, res)
|
||||
|
||||
def test_bin_to_text_from_ipv4_text(self):
|
||||
ipv4_bin = struct.pack('!4B', 10, 28, 197, 1)
|
||||
val = '10.28.197.1'
|
||||
res = ip.bin_to_text(ipv4_bin)
|
||||
eq_(val, res)
|
||||
|
||||
def test_bin_to_text_from_ipv6_text(self):
|
||||
ipv6_bin = struct.pack('!8H', 0x2013, 0xda8, 0x215, 0x8f2, 0xaa20,
|
||||
0x66ff, 0xfe4c, 0x9c3c)
|
||||
val = '2013:da8:215:8f2:aa20:66ff:fe4c:9c3c'
|
||||
res = ip.bin_to_text(ipv6_bin)
|
||||
eq_(val, res)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user