Skip to content

Commit 915ee9e

Browse files
gh-95243: Mitigate the race condition in testSockName (GH-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]> (cherry picked from commit df11012) Co-authored-by: Ross Burton <[email protected]>
1 parent d02e8fb commit 915ee9e

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
@@ -1389,10 +1389,21 @@ def testStringToIPv6(self):
13891389

13901390
def testSockName(self):
13911391
# Testing getsockname()
1392-
port = socket_helper.find_unused_port()
13931392
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13941393
self.addCleanup(sock.close)
1395-
sock.bind(("0.0.0.0", port))
1394+
1395+
# Since find_unused_port() is inherently subject to race conditions, we
1396+
# call it a couple times if necessary.
1397+
for i in itertools.count():
1398+
port = socket_helper.find_unused_port()
1399+
try:
1400+
sock.bind(("0.0.0.0", port))
1401+
except OSError as e:
1402+
if e.errno != errno.EADDRINUSE or i == 5:
1403+
raise
1404+
else:
1405+
break
1406+
13961407
name = sock.getsockname()
13971408
# XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
13981409
# 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)