Skip to content

Enable SO_REUSEADDR whenever it's available #85

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

Closed
wants to merge 1 commit into from
Closed
Changes from all 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
15 changes: 9 additions & 6 deletions adafruit_httpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,15 @@ def serve_forever(

def _set_socket_level_to_reuse_address(self) -> None:
"""
Only for CPython, prevents "Address already in use" error when restarting the server.
On systems that have SO_REUSEADDR, prevents "Address already in use"
error when restarting the server.
"""
self._sock.setsockopt(
self._socket_source.SOL_SOCKET, self._socket_source.SO_REUSEADDR, 1
)
try:
self._sock.setsockopt(
self._socket_source.SOL_SOCKET, self._socket_source.SO_REUSEADDR, 1
)
except AttributeError:
pass

def start(self, host: str, port: int = 80) -> None:
"""
Expand All @@ -220,8 +224,7 @@ def start(self, host: str, port: int = 80) -> None:
self._socket_source.AF_INET, self._socket_source.SOCK_STREAM
)

if implementation.name != "circuitpython":
self._set_socket_level_to_reuse_address()
self._set_socket_level_to_reuse_address()

self._sock.bind((host, port))
self._sock.listen(10)
Expand Down