From e4ea2a4fe3a5294019307b953375a8a9036a1fd1 Mon Sep 17 00:00:00 2001 From: Loren Eteval Date: Sat, 9 Mar 2024 18:18:02 +0800 Subject: [PATCH] Add Tcping.py Signed-off-by: Loren Eteval --- Furious/Library/Tcping.py | 80 +++++++++++++++++++++++++++++++++++++ Furious/Library/__init__.py | 1 + 2 files changed, 81 insertions(+) create mode 100644 Furious/Library/Tcping.py diff --git a/Furious/Library/Tcping.py b/Furious/Library/Tcping.py new file mode 100644 index 0000000..6c12695 --- /dev/null +++ b/Furious/Library/Tcping.py @@ -0,0 +1,80 @@ +# Copyright (C) 2024 Loren Eteval +# +# This file is part of Furious. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import annotations + +from typing import Tuple + +import time +import socket +import ipaddress +import functools + +__all__ = ['tcping'] + + +def tcping( + address: str, + port: int, + timeout: float, + count: int, + interval: float, +) -> Tuple[int, list]: + host = socket.gethostbyname(address) + addressobject = ipaddress.ip_address(host) + + if isinstance(addressobject, ipaddress.IPv4Address): + socketFn = functools.partial( + socket.socket, + family=socket.AF_INET, + type=socket.SOCK_STREAM, + proto=socket.IPPROTO_TCP, + ) + elif isinstance(addressobject, ipaddress.IPv6Address): + socketFn = functools.partial( + socket.socket, + family=socket.AF_INET6, + type=socket.SOCK_STREAM, + proto=socket.IPPROTO_TCP, + ) + else: + raise ValueError('Invalid address') + + sent = 0 + rtts = [] + + for sequence in range(count): + if sequence > 0: + time.sleep(interval) + + with socketFn() as sock: + sock.settimeout(timeout) + + counter = time.perf_counter() + + try: + sock.connect((address, port)) + except Exception: + # Any non-exit exceptions + + pass + else: + sent += 1 + + rtts.append(time.perf_counter() - counter) + + return sent, rtts diff --git a/Furious/Library/__init__.py b/Furious/Library/__init__.py index 6dd6cbb..76f0f23 100644 --- a/Furious/Library/__init__.py +++ b/Furious/Library/__init__.py @@ -17,3 +17,4 @@ from .Configuration import * from .Encoder import * +from .Tcping import *