portpicker
A tiny Rust crate that picks a free network port unused on both TCP and UDP.
Repository Health
Technical Analysis
portpicker is a minimal Rust utility for finding an available network port. Its core function, pick_unused_port(), returns a port that is free on both TCP and UDP, so callers can bind a listener without racing against another process on one protocol while colliding on the other.
Alongside the picker it exposes small predicates — is_free_tcp, is_free_udp, and is_free — for checking whether a specific port is available. It is most commonly used in integration tests and local development tools that need to spin up an ephemeral server on an open port.
What You Get
pick_unused_port()returning a port free on both TCP and UDPis_free_tcp(port)andis_free_udp(port)predicates for a specific portis_free(port)combining both protocol checks- A
Porttype alias overu16for readable signatures - A dependency-light API that binds to both IPv4 and IPv6 unspecified addresses
Common Use Cases
- Allocating an ephemeral port for a server started inside an integration test
- Avoiding port collisions when spinning up multiple local services
- Checking whether a specific port is currently available before binding
Under The Hood
Architecture — The entire crate is a single src/lib.rs. It works by attempting to bind a TcpListener/UdpSocket to the unspecified IPv4 and IPv6 addresses and reading back the local_addr().port(); asking the OS for port 0 yields an ephemeral port, and the is_free_* helpers confirm a candidate port binds successfully on both protocols and both address families before it is handed out.
Tech Stack — Pure Rust (edition 2018) using only std::net for socket binding plus the rand crate to randomize candidate selection. There are no other runtime dependencies.
Code Quality — Extremely small and readable (roughly 2 KB of Rust), with each function doing one obvious thing and returning Option<Port> where binding may fail. The tradeoff of its simplicity is an inherent TOCTOU window — a returned port can be taken by another process before you bind it — which is acceptable for its test-oriented use case. The project is stable but no longer actively developed.
API Design — The API is about as ergonomic as it gets: portpicker::pick_unused_port().expect("No ports free") is the whole story for most users, and the predicate functions read naturally. There is essentially no boilerplate or configuration to learn.
Used by 2 apps in this directory
Hook0
Devops
Open-source Webhooks-as-a-Service: deliver events to your users with auto-retry, signed payloads, and a real-time subscriber dashboard — all without building the infrastructure yourself.
Rivet
AI Agents · Developer Tools
Stateful actors as a primitive for AI agents, real-time collaboration, and durable execution — with in-memory state, WebSockets, queues, and scheduling built in.