inet_free_port (inet_free_port v0.2.0)
View SourceA lightweight Erlang server for finding free TCP and UDP ports within a specified range.
The server keeps internal state for TCP and UDP port ranges and returns the next available port on request.
Ports are checked by attempting to bind using gen_tcp or gen_udp.
If binding succeeds, the port is considered free.
Features
- Supports TCP and UDP
- Configurable port ranges
- Sequential port search
- Lightweight and dependency-free
Example
StartPort = 1000,
EndPort = 2000,
{ok, _Pid} = inet_free_port:start_link(my_port_server, [
{tcp, {StartPort, EndPort}},
{udp, {StartPort, EndPort}}
]).
{ok, TcpPort} = inet_free_port:get_port(my_port_server, tcp).
{ok, UdpPort} = inet_free_port:get_port(my_port_server, udp).
Summary
Functions
Returns a free TCP port using default timeout.
Returns a free TCP or UDP port using default timeout (5000 ms).
Returns a free port.
Handles synchronous requests. Supported calls
Initializes the server state. Internal function. Builds state for TCP and UDP ranges.
Starts the application inet_free_port
Starts a new inet_free_port server.
Stops the application inet_free_port
Functions
-spec get_port(atom() | pid()) -> {ok, inet:port_number()} | {error, term()}.
Returns a free TCP port using default timeout.
-spec get_port(atom() | pid(), tcp | udp) -> {ok, inet:port_number()} | {error, term()}.
Returns a free TCP or UDP port using default timeout (5000 ms).
-spec get_port(atom() | pid(), tcp | udp, timeout()) -> {ok, inet:port_number()} | {error, term()}.
Returns a free port.
Parameters
Server- Server name or pidType-tcporudpTimeout- timeout in milliseconds returns{ok, Port}or{error, Reason}
-spec handle_call(term(), {pid(), term()}, map()) -> {reply, term(), map()} | {stop, term(), term(), map()}.
Handles synchronous requests. Supported calls:
{get_port, tcp | udp}– returns a free portstop– stops the server
-spec init([proplists:proplist()]) -> {ok, map()}.
Initializes the server state. Internal function. Builds state for TCP and UDP ranges.
Starts the application inet_free_port
-spec start_link(atom(), proplists:proplist()) -> {ok, pid()} | {error, term()}.
Starts a new inet_free_port server.
Name- Local registered name of the serverParam- Proplist with configuration:
If range is invalid, defaults to[ {tcp, {StartPort, EndPort}}, {udp, {StartPort, EndPort}} ]1..65535.
-spec stop(term()) -> ok.
Stops the application inet_free_port