inet_free_port (inet_free_port v0.2.0)

View Source

A 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

get_port(Server)

-spec get_port(atom() | pid()) -> {ok, inet:port_number()} | {error, term()}.

Returns a free TCP port using default timeout.

get_port(Server, Type)

-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).

get_port(Server, Type, Timeout)

-spec get_port(atom() | pid(), tcp | udp, timeout()) -> {ok, inet:port_number()} | {error, term()}.

Returns a free port.

Parameters

  • Server - Server name or pid
  • Type - tcp or udp
  • Timeout - timeout in milliseconds returns {ok, Port} or {error, Reason}

handle_call/3

-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 port

  • stop – stops the server

init/1

-spec init([proplists:proplist()]) -> {ok, map()}.

Initializes the server state. Internal function. Builds state for TCP and UDP ranges.

start(StartType, StartArgs)

-spec start(term(), term()) -> {ok, pid()} | {error, term()}.

Starts the application inet_free_port

start_link(Name, Param)

-spec start_link(atom(), proplists:proplist()) -> {ok, pid()} | {error, term()}.

Starts a new inet_free_port server.

  • Name - Local registered name of the server
  • Param - Proplist with configuration:
    [
    {tcp, {StartPort, EndPort}},
    {udp, {StartPort, EndPort}}
    ]
    If range is invalid, defaults to 1..65535.

stop(State)

-spec stop(term()) -> ok.

Stops the application inet_free_port