From 0adce826b151752631029145accf07c169bb97be Mon Sep 17 00:00:00 2001 From: Prodesire Date: Tue, 12 Dec 2017 11:11:52 +0800 Subject: [PATCH] is_ipv4 is for all platforms, is_ipv6 is only for POSIX --- pydu/network.py | 30 +++++++++++++++--------------- tests/test_network.py | 9 +++++---- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/pydu/network.py b/pydu/network.py index b9efb56..0b100ca 100644 --- a/pydu/network.py +++ b/pydu/network.py @@ -1,5 +1,6 @@ import socket import struct +from pydu.platform import POSIX # https://github.com/kennethreitz/requests/blob/master/requests/utils.py @@ -13,31 +14,30 @@ def dotted_netmask(mask): return socket.inet_ntoa(struct.pack('>I', bits)) +# https://github.com/kennethreitz/requests/blob/master/requests/utils.py def is_ipv4(ip): """ Returns True if the IPv4 address ia valid, otherwise returns False. """ - return _is_ip(ip, af=socket.AF_INET) - - -def is_ipv6(ip): - """ - Returns True if the IPv6 address ia valid, otherwise returns False. - """ - return _is_ip(ip, af=socket.AF_INET6) - - -def _is_ip(ip, af): - ''' - Returns True if the IP address ia valid, otherwise returns False. - ''' try: - socket.inet_pton(af, ip) + socket.inet_aton(ip) except socket.error: return False return True +if POSIX: + def is_ipv6(ip): + """ + Returns True if the IPv6 address ia valid, otherwise returns False. + """ + try: + socket.inet_pton(socket.AF_INET6, ip) + except socket.error: + return False + return True + + def get_free_port(): s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM) s.bind(('127.0.0.1', 0)) diff --git a/tests/test_network.py b/tests/test_network.py index 4419f1c..41b6c19 100644 --- a/tests/test_network.py +++ b/tests/test_network.py @@ -1,6 +1,8 @@ import pytest -from pydu.platform import WINDOWS -from pydu.network import dotted_netmask, is_ipv4, is_ipv6, get_free_port +from pydu.platform import POSIX +from pydu.network import dotted_netmask, is_ipv4, get_free_port +if POSIX: + from pydu.network import is_ipv6 @pytest.mark.parametrize( @@ -13,7 +15,6 @@ def test_dotted_netmask(mask, expected): assert dotted_netmask(mask) == expected -@pytest.mark.skipif(WINDOWS, reason='Not support on windows') class TestIsIPv4Address: def test_valid(self): @@ -24,7 +25,7 @@ class TestIsIPv4Address: assert not is_ipv4(value) -@pytest.mark.skipif(WINDOWS, reason='Not support on windows') +@pytest.mark.skipif(not POSIX, reason='Not support on No-POSIX system') class TestIsIPv6Address: def test_valid(self):