Skip to content

Get ephemeral port number after binding to port 0 #833

@rgov

Description

@rgov

Listening on port 0 will ask the system to bind on an unused port in the ephemeral port range. For example, I can run MediaMTX with rtspAddress: :0 which logs

2025/07/17 22:48:57 INF [RTSP] listener opened on :0 (TCP)

In reality the operating system assigned it port 60780:

% sudo lsof -nP -iTCP -sTCP:LISTEN
COMMAND     PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
mediamtx  53024    rgov   4u  IPv6   0x4c4d05e23c32f8      0t0  TCP *:60780 (LISTEN)

I think in server_tcp_listener:initialize() after calling Server.Listen(), you would extract the port number like this:

// I don't write Go...
port := sl.ln.Addr().(*net.TCPAddr).Port

There probably should be an interface for exposing the port back to functions like printAddresses() rather than have them rummage around in srv.serverTCPListener.ln which is marked private.

Why? I'd like to run an ephemeral RTSP server as part of a unit test of a video streaming application. It wouldn't do to use a static port; it could be in use (consider a buildbot that is running tests on multiple branches at once). If I pick a random port, there's a chance of collision / race condition. Allowing the system to choose by setting port = 0 and parsing the log message is the robust solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions