Systems programming · concurrency
A TCP port scanner in Rust, rewritten three times
I wanted to learn Rust on something useful, so I wrote a port scanner, then rewrote it twice once I understood why the previous version was slow or wasteful.
- Period
- Summer 2026 · three weeks
- Status
- Completed · personal project
- Type
- Personal project
The project
I wanted to learn Rust on a security-related problem while I was getting to grips with ownership, borrowing and concurrency. The starting point was simple: with a 10 ms timeout per connection, testing all 65,535 ports one by one can take hours. I wanted to go faster without wasting the machine's resources, and above all to understand what each improvement costs.
- Version 1: a sequential loop with connect_timeout.
- Version 2: ports split across OS threads, results sent back over an mpsc channel. The total time then depends on the busiest thread.
- Version 3: lightweight async tasks with Tokio, and a semaphore capping simultaneous connections at 5,000 so the system and the network are not flooded.
What I did, and what went wrong
- Wrote the three versions in sequence, keeping the earlier ones as comments before turning them back into standalone files for the repository.
- Documented the cost of each approach: about 2 MB of stack per OS thread, plus creation and scheduling overhead, against much lighter async tasks.
What went wrong
- Version 2 was fast (under a second with 1,000 threads, in my tests) but spending 1,000 threads on a few seconds of work is a poor trade. Accepting that a working solution was still the wrong one is what led to version 3.
How I checked it
What I wanted to prove, the test I ran, and what I actually saw.
| What I wanted to prove | The test | What I saw |
|---|---|---|
| Async version is faster and lighter | Timed full-range scans of each version on my machine | About 0.13 s for 65,535 ports with 5,000 tasks (informal measurement) |
Result
- Three working versions and a written comparison of threads with channels versus async tasks.
- A habit I kept: question a working solution when its cost is out of proportion.
Limits and next steps
- TCP connect scan only; no service detection.
- Timings are informal: I didn't record the target or the network conditions, so they only give orders of magnitude.
- To be used only on systems I own or am authorised to test.
What I would do next
- A reproducible benchmark (fixed target, repeated runs, median)
- Command-line arguments instead of interactive input
- Basic banner grabbing
Code and documents
- Repository: the three versions github.com/AGRO-Rachidi/port-scanner-rust