diff options
-rw-r--r-- | netlib/utils.py | 29 | ||||
-rw-r--r-- | netlib/version.py | 1 | ||||
-rw-r--r-- | test/test_utils.py | 19 |
3 files changed, 45 insertions, 4 deletions
diff --git a/netlib/utils.py b/netlib/utils.py index 61fd54ae..00e1cd12 100644 --- a/netlib/utils.py +++ b/netlib/utils.py @@ -1,3 +1,5 @@ +import socket + def isascii(s): try: @@ -32,9 +34,9 @@ def hexdump(s): """ parts = [] for i in range(0, len(s), 16): - o = "%.10x"%i - part = s[i:i+16] - x = " ".join("%.2x"%ord(i) for i in part) + o = "%.10x" % i + part = s[i:i + 16] + x = " ".join("%.2x" % ord(i) for i in part) if len(part) < 16: x += " " x += " ".join(" " for i in range(16 - len(part))) @@ -42,3 +44,24 @@ def hexdump(s): (o, x, cleanBin(part, True)) ) return parts + + +def inet_ntop(address_family, packed_ip): + if hasattr(socket, "inet_ntop"): + return socket.inet_ntop(address_family, packed_ip) + # Windows Fallbacks + if address_family == socket.AF_INET: + return socket.inet_ntoa(packed_ip) + if address_family == socket.AF_INET6: + ip = packed_ip.encode("hex") + return ":".join([ip[i:i + 4] for i in range(0, len(ip), 4)]) + + +def inet_pton(address_family, ip_string): + if hasattr(socket, "inet_pton"): + return socket.inet_pton(address_family, ip_string) + # Windows Fallbacks + if address_family == socket.AF_INET: + return socket.inet_aton(ip_string) + if address_family == socket.AF_INET6: + return ip_string.replace(":", "").decode("hex")
\ No newline at end of file diff --git a/netlib/version.py b/netlib/version.py index 1d3250e1..25565d40 100644 --- a/netlib/version.py +++ b/netlib/version.py @@ -1,4 +1,5 @@ IVERSION = (0, 11) VERSION = ".".join(str(i) for i in IVERSION) +MINORVERSION = ".".join(str(i) for i in IVERSION[:2]) NAME = "netlib" NAMEVERSION = NAME + " " + VERSION diff --git a/test/test_utils.py b/test/test_utils.py index 61820a81..a9a48cd0 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -1,5 +1,5 @@ from netlib import utils - +import socket def test_hexdump(): assert utils.hexdump("one\0"*10) @@ -11,3 +11,20 @@ def test_cleanBin(): assert utils.cleanBin("\nne") == "\nne" assert utils.cleanBin("\nne", True) == ".ne" +def test_ntop_pton(): + for family, ip_string, packed_ip in ( + (socket.AF_INET, + "127.0.0.1", + "\x7f\x00\x00\x01"), + (socket.AF_INET6, + "2001:0db8:85a3:08d3:1319:8a2e:0370:7344", + " \x01\r\xb8\x85\xa3\x08\xd3\x13\x19\x8a.\x03psD")): + assert ip_string == utils.inet_ntop(family, packed_ip) + assert packed_ip == utils.inet_pton(family, ip_string) + if hasattr(socket, "inet_ntop"): + ntop, pton = socket.inet_ntop, socket.inet_pton + delattr(socket,"inet_ntop") + delattr(socket,"inet_pton") + assert ip_string == utils.inet_ntop(family, packed_ip) + assert packed_ip == utils.inet_pton(family, ip_string) + socket.inet_ntop, socket.inet_pton = ntop, pton
\ No newline at end of file |