From 854bbc49f1695596ee543b2abae5d22f5ed8d3b0 Mon Sep 17 00:00:00 2001 From: Sandip Pandey Date: Wed, 24 Jan 2024 13:32:05 +0100 Subject: [PATCH] Set socket reuseaddr to true while checking free port --- src/tribler/core/utilities/network_utils.py | 1 + src/tribler/core/utilities/tests/test_network_utils.py | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/src/tribler/core/utilities/network_utils.py b/src/tribler/core/utilities/network_utils.py index 29e3d74223b..4284213c739 100644 --- a/src/tribler/core/utilities/network_utils.py +++ b/src/tribler/core/utilities/network_utils.py @@ -74,6 +74,7 @@ def is_port_free(self, port): try: for socket_class in self.socket_class_set: with socket_class() as s: + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', port)) return True except OSError: diff --git a/src/tribler/core/utilities/tests/test_network_utils.py b/src/tribler/core/utilities/tests/test_network_utils.py index 7eb8ae5e140..5c1af8d84f8 100644 --- a/src/tribler/core/utilities/tests/test_network_utils.py +++ b/src/tribler/core/utilities/tests/test_network_utils.py @@ -1,3 +1,5 @@ +import socket + import pytest from tribler.core.utilities.network_utils import FreePortNotFoundError, NetworkUtils @@ -18,6 +20,11 @@ def bind(self, host_port): finally: self.bound_ports.add(port) + def setsockopt(self, level, option_name, option_value): + assert level == socket.SOL_SOCKET + assert option_name == socket.SO_REUSEADDR + assert option_value == 1 + def __enter__(self): return self