Added feature for validating addresses
This commit is contained in:
+49
-1
@@ -14,6 +14,8 @@
|
||||
|
||||
import os
|
||||
from typing import Tuple, Literal, Sequence
|
||||
import ipaddress
|
||||
import socket
|
||||
|
||||
__all__ = [
|
||||
'is_number',
|
||||
@@ -153,4 +155,50 @@ def create_file_if_not_exists(path: str, content: bytes = b''):
|
||||
if not os.path.exists(path):
|
||||
with open(path, 'wb') as f:
|
||||
f.write(content)
|
||||
f.close()
|
||||
f.close()
|
||||
|
||||
def is_valid_host(host: str) -> bool:
|
||||
'''
|
||||
Checks whether the host is a valid IP address.
|
||||
|
||||
:param host: The host
|
||||
:type host: str
|
||||
|
||||
:return: ``True`` if the host is a valid IP address, otherwise ``False``
|
||||
:rtype: bool
|
||||
'''
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def is_valid_port(port: str) -> bool:
|
||||
'''
|
||||
Checks whether the port is a valid port number.
|
||||
|
||||
:param port: The port
|
||||
:type port: str
|
||||
|
||||
:return: ``True`` if the port is a valid port number, otherwise ``False``
|
||||
:rtype: bool
|
||||
'''
|
||||
if not port.isdigit():
|
||||
return False
|
||||
port_num = int(port)
|
||||
return 1 <= port_num <= 65535
|
||||
|
||||
def validate_address_port(addr: str) -> bool:
|
||||
if ':' not in addr:
|
||||
return False
|
||||
|
||||
if addr.startswith('['):
|
||||
try:
|
||||
host, port = addr.rsplit(']:', 1)
|
||||
host = host[1:]
|
||||
except ValueError:
|
||||
return False
|
||||
else:
|
||||
host, port = addr.rsplit(':', 1)
|
||||
|
||||
return is_valid_host(host) and is_valid_port(port)
|
||||
Reference in New Issue
Block a user