summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorShinpei Muraoka <shinpei.muraoka@gmail.com>2016-10-27 09:55:18 +0900
committerFUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>2016-10-29 06:31:53 +0900
commitec1749beca1faa6dd1487a0b6e4aaad23caf0685 (patch)
tree7a0fc7c5d193d21a37429755aa28370db57c987a
parentdf1434a9bbb25666a0c1aa00d3d5ee27ead418d9 (diff)
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>
-rw-r--r--ryu/lib/ip.py31
-rw-r--r--ryu/tests/unit/lib/test_ip.py26
2 files changed, 57 insertions, 0 deletions
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)