From ec1749beca1faa6dd1487a0b6e4aaad23caf0685 Mon Sep 17 00:00:00 2001 From: Shinpei Muraoka Date: Thu, 27 Oct 2016 09:55:18 +0900 Subject: lib/ip: Add method to convert the format of Ipv4 or Ipv6 Signed-off-by: Shinpei Muraoka Signed-off-by: FUJITA Tomonori --- ryu/lib/ip.py | 31 +++++++++++++++++++++++++++++++ ryu/tests/unit/lib/test_ip.py | 26 ++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/ryu/lib/ip.py b/ryu/lib/ip.py index 6630418d..130a844d 100644 --- a/ryu/lib/ip.py +++ b/ryu/lib/ip.py @@ -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 diff --git a/ryu/tests/unit/lib/test_ip.py b/ryu/tests/unit/lib/test_ip.py index d9716c8a..3fb78119 100644 --- a/ryu/tests/unit/lib/test_ip.py +++ b/ryu/tests/unit/lib/test_ip.py @@ -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) -- cgit v1.2.3