is_ipv4 is for all platforms, is_ipv6 is only for POSIX

This commit is contained in:
Prodesire 2017-12-12 11:11:52 +08:00
parent 8bd61a13d8
commit 0adce826b1
2 changed files with 20 additions and 19 deletions

View File

@ -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))

View File

@ -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):