Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply SO_REUSEADDR to test server's socket #4393

Merged
merged 4 commits into from
Nov 27, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
6 changes: 6 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,17 @@
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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will be nice if you add a comment describing why it is set here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

not everyone knows that it has different semantics under Windows.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, I mean another thing ;). I don't understand why it ever needs. Even in Linux.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because if you retry binding to the same socket fast enough, it'll fail. Even from the same process (after unbinding). There's some sort of timeout in place.

OTOH if you were to always use an ephemeral port 0, the kernel would allocate you a different port each time and there wouldn't be such a problem.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I confused. I misread as SO_REUSEPORT.

asvetlov marked this conversation as resolved.
Show resolved Hide resolved
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
return s

Expand Down