From 1d11f2aadc5c22a000131635480ef6db0a9e9b3c Mon Sep 17 00:00:00 2001 From: Prodesire Date: Tue, 23 Jan 2018 20:14:02 +0800 Subject: [PATCH] update doc for network --- docs/network.rst | 20 ++++++++++++++++++++ pydu/network.py | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/docs/network.rst b/docs/network.rst index 7be09fb..e4f72b6 100644 --- a/docs/network.rst +++ b/docs/network.rst @@ -42,3 +42,23 @@ Network >>> from pydu.network import get_free_port >>> get_free_port() 57118 + + +.. py:function:: pydu.network.ip2int(ip_str) + + Convert ip to integer. Support IPV4 and IPV6. + Raise ``ValueError`` if convert failed. + + >>> from pydu.network import ip2int + >>> ip2int('10.1.1.1') + 167837953 + + +.. py:function:: pydu.network.int2ip(ip_int) + + Convert integer to ip. Support IPV4 and IPV6. + Raise ``ValueError`` if convert failed. + + >>> from pydu.network import int2ip + >>> int2ip(167837953) + '10.1.1.1' diff --git a/pydu/network.py b/pydu/network.py index 0fe951b..f00b578 100644 --- a/pydu/network.py +++ b/pydu/network.py @@ -123,6 +123,10 @@ def get_free_port(): # https://stackoverflow.com/questions/5619685/conversion-from-ip-string-to-integer-and-backward-in-python # https://stackoverflow.com/questions/11894717/python-convert-ipv6-to-an-integer def ip2int(ip_str): + """ + Convert ip to integer. Support IPV4 and IPV6. + Raise `ValueError` if convert failed. + """ try: return struct.unpack("!I", socket.inet_aton(ip_str))[0] except socket.error: @@ -138,6 +142,10 @@ def ip2int(ip_str): # https://stackoverflow.com/questions/5619685/conversion-from-ip-string-to-integer-and-backward-in-python def int2ip(ip_int): + """ + Convert integer to ip. Support IPV4 and IPV6. + Raise `ValueError` if convert failed. + """ try: return socket.inet_ntoa(struct.pack("!I", ip_int)) except (socket.error, struct.error):