Skip to content

Commit df11012

Browse files
authored
gh-95243: Mitigate the race condition in testSockName (#96173)
find_unused_port() has an inherent race condition, but we can't use bind_port() as that uses .getsockname() which this test is exercising. Try binding to unused ports a few times before failing. Signed-off-by: Ross Burton <[email protected]>
1 parent e34c82a commit df11012

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

Lib/test/test_socket.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1398,10 +1398,21 @@ def testStringToIPv6(self):
13981398

13991399
def testSockName(self):
14001400
# Testing getsockname()
1401-
port = socket_helper.find_unused_port()
14021401
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
14031402
self.addCleanup(sock.close)
1404-
sock.bind(("0.0.0.0", port))
1403+
1404+
# Since find_unused_port() is inherently subject to race conditions, we
1405+
# call it a couple times if necessary.
1406+
for i in itertools.count():
1407+
port = socket_helper.find_unused_port()
1408+
try:
1409+
sock.bind(("0.0.0.0", port))
1410+
except OSError as e:
1411+
if e.errno != errno.EADDRINUSE or i == 5:
1412+
raise
1413+
else:
1414+
break
1415+
14051416
name = sock.getsockname()
14061417
# XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
14071418
# it reasonable to get the host's addr in addition to 0.0.0.0.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Mitigate the inherent race condition from using find_unused_port() in
2+
testSockName() by trying to find an unused port a few times before failing.
3+
Patch by Ross Burton.

0 commit comments

Comments
 (0)