From 6c63153fc03a92b32bc73ed2b2365e6b2b693f90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Doktor?= Date: Fri, 7 Dec 2018 13:16:05 +0100 Subject: [PATCH] avocado.utils.network: Optimize is_port_free a bit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We do quite a few loops, let's use boolean instead of string comparison. Signed-off-by: Lukáš Doktor --- avocado/utils/network.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/avocado/utils/network.py b/avocado/utils/network.py index 7b33adac..8256c169 100644 --- a/avocado/utils/network.py +++ b/avocado/utils/network.py @@ -38,18 +38,20 @@ def is_port_free(port, address): :param port: Port number :param address: Socket address to bind or connect """ - sock = None - if address == "localhost": + if address == "localhost" or not address: + localhost = True protocols = PROTOCOLS else: + localhost = False # sock.connect always connects for UDP protocols = (socket.SOCK_STREAM, ) + sock = None try: for family in FAMILIES: for protocol in protocols: try: sock = socket.socket(family, protocol) - if address == "localhost": + if localhost: sock.bind(("", port)) else: sock.connect((address, port)) @@ -57,7 +59,7 @@ def is_port_free(port, address): except socket.error as exc: if exc.errno in (93, 94): # Unsupported combinations continue - if address == "localhost": + if localhost: return False sock.close() return True -- GitLab