Skip to content

feat: auto-assign free port when setPort(0) is called#848

Draft
ithewei with Copilot wants to merge 3 commits into
masterfrom
copilot/add-auto-apply-free-port-functionality
Draft

feat: auto-assign free port when setPort(0) is called#848
ithewei with Copilot wants to merge 3 commits into
masterfrom
copilot/add-auto-apply-free-port-functionality

Conversation

Copilot AI commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

setPort() with no arguments (port=0) previously had no effect — the server would not listen on any port. This adds OS-level free-port auto-assignment by binding to port 0, then retrieving the actual assigned port via getsockname().

Semantic changes

  • port/https_port default: 0-1-1 now means "not configured"; 0 means "let OS assign a free port" (consistent with standard socket API convention)
  • setPort() ssl_port default: 0-1 — prevents setPort(8080) from inadvertently resetting https_port
  • start() return value — now returns the actual HTTP port number on success (was always 0), enabling int real_port = server.start()

Usage

server.setHost("127.0.0.1");
server.setPort();               // port=0: OS picks a free port
server.setThreadNum(4);
int real_port = server.start(); // returns the actual assigned port

Affected files

  • http/server/HttpServer.h — default port sentinel, setPort() signature, start() return value + doc comment
  • http/server/HttpServer.cpp — condition port > 0port >= 0; getsockname() call after Listen(0, ...); #include "hsocket.h" added; error logged on getsockname failure
  • examples/httpd/httpd.cpp — "no port configured" guard: == 0< 0
  • docs/cn/HttpServer.md — updated signatures and start() description

Copilot AI linked an issue Jul 10, 2026 that may be closed by this pull request
Copilot AI changed the title [WIP] Add automatic application of free port functionality feat: auto-assign free port when setPort(0) is called Jul 10, 2026
Copilot AI requested a review from ithewei July 10, 2026 11:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

能否增加自动应用空闲端口的功能

2 participants