Skip to content

Commit

Permalink
[3.7] Apply SO_REUSEADDR to test server's socket (#4393) (#4396)
Browse files Browse the repository at this point in the history
(cherry picked from commit b38e65a)

Co-authored-by: Andrew Svetlov <[email protected]>
  • Loading branch information
asvetlov authored Nov 27, 2019
1 parent 1a5d806 commit 5905fb9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGES/4393.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Apply SO_REUSEADDR to test server's socket.
9 changes: 9 additions & 0 deletions aiohttp/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import functools
import gc
import inspect
import os
import socket
import sys
import unittest
Expand Down Expand Up @@ -57,12 +58,20 @@
SSLContext = None


REUSE_ADDRESS = os.name == 'posix' and sys.platform != 'cygwin'


def get_unused_port_socket(host: str) -> socket.socket:
return get_port_socket(host, 0)


def get_port_socket(host: str, port: int) -> socket.socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if REUSE_ADDRESS:
# Windows has different semantics for SO_REUSEADDR,
# so don't set it. Ref:
# https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
return s

Expand Down

0 comments on commit 5905fb9

Please sign in to comment.