random-port

Find an available TCP or UDP network port in Rust

Library
Cargo
v0.1.1
2stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
13/100Needs Attention
Development Activity0
Maintenance0
Community4
Maturity48
Momentum0

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
74/100Good
Architecture72
Code Quality68
Innovation66
Learning Curve88

random-port is a small Rust crate that finds an available network port on the local machine. Its builder-style PortPicker lets you scan a configurable port range, exclude specific ports, target a particular host and protocol, and choose either the first free port or a random one.

It is a handy utility for spinning up test servers, allocating ephemeral ports for local development, or avoiding port collisions in tooling, returning a ready-to-bind u16 with a single call.

What You Get

  • A PortPicker builder with a single pick() call returning an available u16
  • Configurable port_range restricted to the 1024..=65535 space
  • Exclusion of specific ports via exclude and exclude_add
  • Protocol targeting for TCP, UDP, or both
  • Host selection and optional random (rather than first-available) port choice

Common Use Cases

  • Allocating an ephemeral port for a test server or integration test
  • Picking a free port for a local development service
  • Avoiding port collisions when launching multiple processes
  • Selecting a random available port within a constrained range

Under The Hood

Architecture - The crate exposes a PortPicker builder that accumulates constraints (range, exclusions, host, protocol, random flag) and, on pick(), iterates candidate ports and probes each for availability by attempting to bind the requested protocol(s) on the target host. It returns the first (or a random) port that binds successfully, or an Error when the range is exhausted.

Tech Stack - Pure Rust built on the standard library’s networking primitives for TCP and UDP binding, with no heavyweight dependencies. It is published to crates.io and installable via cargo add.

Code Quality - The crate is intentionally small with a focused single-responsibility surface. Documentation lives in a concise README enumerating each builder method; there is minimal ceremony around a straightforward bind-probe loop.

API Design - The builder pattern reads naturally: construct a PortPicker, chain constraints like port_range, exclude, protocol, and host, then call pick(). Sensible defaults (all local addresses, both protocols, first-available) keep the zero-config case to a single line while still allowing precise control.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search