From f89b6445ff70f45907ab4077844dbd1319a4794d Mon Sep 17 00:00:00 2001 From: Jakob Scheid Date: Sat, 28 Feb 2026 03:07:33 +0100 Subject: [PATCH] Added feature for validating addresses --- README.md | 3 +++ pyproject.toml | 2 +- src/jeb_utils/utils.py | 50 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 781df25..1a995ec 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,9 @@ pip install jeb-utils --index-url https://repo.jcloud-services.ddns.net/simple/ - `create_file_if_not_exists`: Creates a file if it does not exist. ## Changelog +### Version 0.2.1 +- Added feature for validating addresses. + ### Version 0.2.0 - Removed all the functions and classes that are now in jeb-server-utils. diff --git a/pyproject.toml b/pyproject.toml index dcb16f7..c70e41f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "jeb-utils" -version = "0.2.0" +version = "0.2.1" description = "Common utils for JEB client and server." dependencies = ["cryptography"] license = "Apache-2.0" \ No newline at end of file diff --git a/src/jeb_utils/utils.py b/src/jeb_utils/utils.py index 44e210d..bbda3f6 100644 --- a/src/jeb_utils/utils.py +++ b/src/jeb_utils/utils.py @@ -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() \ No newline at end of file + 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) \ No newline at end of file