Skip to content

Commit e1d3e3b

Browse files
committed
Added method for verifying that server can be started on given host:port
1 parent e5f506b commit e1d3e3b

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

adafruit_httpserver/server.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,17 @@ def route_decorator(func: Callable) -> Callable:
8989

9090
return route_decorator
9191

92+
def _verify_can_start(self, host: str, port: int) -> None:
93+
"""Check if the server can be successfully started. Raises RuntimeError if not."""
94+
95+
if host is None or port is None:
96+
raise RuntimeError("Host and port cannot be None")
97+
98+
try:
99+
self._socket_source.getaddrinfo(host, port)
100+
except OSError as error:
101+
raise RuntimeError(f"Cannot start server on {host}:{port}") from error
102+
92103
def serve_forever(self, host: str, port: int = 80) -> None:
93104
"""
94105
Wait for HTTP requests at the given host and port. Does not return.
@@ -116,6 +127,8 @@ def start(self, host: str, port: int = 80) -> None:
116127
:param str host: host name or IP address
117128
:param int port: port
118129
"""
130+
self._verify_can_start(host, port)
131+
119132
self.stopped = False
120133
self._sock = self._socket_source.socket(
121134
self._socket_source.AF_INET, self._socket_source.SOCK_STREAM

0 commit comments

Comments
 (0)