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

Return correct port if dynamic port allocation is used #901

Merged
merged 1 commit into from
Sep 29, 2024
Merged
Show file tree
Hide file tree
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: 14 additions & 1 deletion include/crow/app.h
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,20 @@ namespace crow
/// \brief Get the port that Crow will handle requests on
std::uint16_t port() const
{
return port_;
if (!server_started_)
{
return port_;
}
#ifdef CROW_ENABLE_SSL
if (ssl_used_)
{
return ssl_server_->port();
}
else
#endif
{
return server_->port();
}
}

/// \brief Set the connection timeout in seconds (default is 5)
Expand Down
4 changes: 4 additions & 0 deletions include/crow/http_server.h
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ namespace crow // NOTE: Already documented in "crow/app.h"
io_service_.stop(); // Close main io_service
}

uint16_t port(){
return acceptor_.local_endpoint().port();
}

/// Wait until the server has properly started
void wait_for_start()
{
Expand Down
18 changes: 18 additions & 0 deletions tests/unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,24 @@ TEST_CASE("server_handling_error_request")
app.stop();
} // server_handling_error_request

TEST_CASE("server_dynamic_port_allication")
{
SimpleApp app;
CROW_ROUTE(app, "/")
([] {
return "A";
});
auto _ = app.bindaddr(LOCALHOST_ADDRESS).port(0).run_async();
app.wait_for_server_start();
asio::io_service is;
{
asio::ip::tcp::socket c(is);
c.connect(asio::ip::tcp::endpoint(
asio::ip::address::from_string(LOCALHOST_ADDRESS), app.port()));
}
app.stop();
} // server_dynamic_port_allication

TEST_CASE("server_handling_error_request_http_version")
{
static char buf[2048];
Expand Down
Loading