Finds an available local TCP port.
Intended for local development, where running several applications at once should not require hand-editing port numbers.
config :my_app, MyAppWeb.Endpoint,
http: [
ip: {127, 0, 0, 1},
port: AutoPort.find(4000)
]find/2 accepts either a starting port, in which case it probes upwards
until it finds a free port, or a range, in which case it only probes ports
within that range and raises when none is free.
Options
:ip- the interface to test the port on. Defaults to{127, 0, 0, 1}.:verbose- whether to print a message when the requested port is unavailable. Defaults totrue.:env- the environment variable that overrides the target, orfalseto ignore the environment. Defaults to"PORT".
Environment override
When PORT is set it replaces the target, so PORT=4050 iex -S mix phx.server
starts the search at 4050 instead of the port written in the config. The
search still walks upwards from there, so two shells with the same PORT do
not collide. Pass env: false to bind the configured target only.
Summary
Functions
Returns whether port can be bound on the given interface.
Returns {:ok, port} with the first available port at or after target,
or {:error, message} when every candidate port is taken.
Returns the first available port at or after target, raising when there is none.
Types
@type option() :: {:ip, :inet.socket_address()} | {:verbose, boolean()} | {:env, String.t() | false}
@type port_number() :: 1..65535
@type target() :: port_number() | Range.t()
Functions
@spec available?(port_number(), [option()]) :: boolean()
Returns whether port can be bound on the given interface.
Options
:ip- the interface to test the port on. Defaults to{127, 0, 0, 1}.
@spec fetch(target(), [option()]) :: {:ok, port_number()} | {:error, String.t()}
Returns {:ok, port} with the first available port at or after target,
or {:error, message} when every candidate port is taken.
@spec find(target(), [option()]) :: port_number()
Returns the first available port at or after target, raising when there is none.
Examples
AutoPort.find(4000)
#=> 4000
AutoPort.find(4000..4010, verbose: false)
#=> 4001