Notes
One attempt
Everything rests on one small function. Create a TCP socket, set a timeout, and try to connect. Connect ex returns zero if the connection succeeded, which means the port is open. A closed port refuses immediately with an error. A filtered port says nothing at all, and the call waits until the timeout expires. The finally block closes the socket whatever happens, so a scan of thousands of ports does not leak thousands of open sockets.
import socket
def check(host, port, timeout):
s = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
ok = s.connect_ex((host, port)) == 0
return port, ok
finally:
s.close() Many at once
Checking ports one after another works, but each filtered port costs a full timeout. So we run many attempts at once with a thread pool. Threads suit this job well, because each one spends nearly all its time waiting on the network. Pool map hands each port number to the check function and returns the results in order, and a list comprehension keeps the ports that answered. That is the whole scanning engine.
from concurrent.futures import (
ThreadPoolExecutor)
with ThreadPoolExecutor(100) as pool:
results = pool.map(
lambda p: check(host, p, 0.5),
range(lo, hi + 1))
open_ports = [
p for p, ok in results if ok] Make it a tool
A few lines of argparse turn the functions into a tool. The host is required. The port range, the timeout and the number of workers are options with sensible defaults. Argparse also gives you a help message and error handling for free. This is the difference between a snippet and something a colleague can use: they can run it with minus minus help and understand it without reading the code.
p = argparse.ArgumentParser()
p.add_argument("host")
p.add_argument("--ports",
default="1-1024")
p.add_argument("--timeout",
type=float, default=0.5)
p.add_argument("--workers",
type=int, default=100)
a = p.parse_args()
lo, hi = (int(x) for x in
a.ports.split("-")) Run it
Here is a real run against the local machine, where we had started two test listeners: a web server on port eight thousand and eighty, and a small program on port two thousand two hundred and twenty two that sends an SSH-style banner. The scanner checked ten thousand ports in one point one five seconds and found three open, including one we had not started ourselves. That surprise is exactly why you scan your own machines: you find services you did not know were running.
$ python3 scan.py 127.0.0.1 \
--ports 1-10000
2024/tcp open
2222/tcp open SSH-2.0-OpenSSH_9.6 lab
8080/tcp open
scanned 10000 ports in 1.15s, 3 open
# 2222: a test listener that
# sends an SSH-style banner
# 8080: python3 -m http.server Why scans get slow
One result surprised us and teaches something. With a single worker instead of a hundred, the same scan took almost the same time. Why? On the local machine every closed port refuses instantly, so there is nothing to wait for. Behind a firewall that silently drops packets, every port costs the full timeout. Ten thousand ports at half a second each is eighty three minutes one at a time, and under a minute with a hundred workers. Timeouts, not CPU, decide how long a scan takes.
- on loopback, closed ports refuse at once: 100 workers and 1 worker both took about 1 second
- behind a firewall that drops packets, each port waits the full timeout
- 10,000 ports x 0.5 s = 83 minutes, one at a time
- with 100 workers: under a minute
What Nmap adds
Be clear about what this version does not do. It is a connect scan, so it completes the handshake and services log it. It reports open or not open, without separating closed from filtered, though you could by examining the error code. It is TCP only. It has no probes for quiet services and no version detection. It does not adapt its timing to the network. Nmap does all of that with twenty years of tuning, which is why you use Nmap for real work.
- connect scan only: completes the handshake, so services log it
- open vs not-open: cannot tell closed from filtered
- TCP only, no UDP
- no service probes or version detection
- no adaptive timing or retries
- Nmap does all of these, with 20 years of tuning
Be a good neighbour
A scanner you wrote yourself is still a scanner, and the rules from the Nmap episode apply in full. Use it only on your own lab, systems you own, or targets in a written scope. Keep the worker count modest on real networks, because hundreds of simultaneous connections can upset old or fragile devices. Expect the security team to notice. Keep a record of what you scanned and when. The first line of the script says all this, deliberately.
- only your own lab, systems you own, or a written scope
- keep workers modest on real networks: a flood of connections can upset old devices
- expect the SOC to see it
- log what you scanned and when the docstring says so, on purpose
Where this is useful
So where is this useful? As a building block inside your own checks. A pipeline step that asks whether the database port is reachable from the public network, and fails the build if it is. A quick test on a server that has no tools installed but does have Python. Verifying a firewall change did what you intended. A small job that watches for a new open port and raises an alert. You now understand the mechanism well enough to build any of those.
- a pipeline check: "is the database port reachable from the public subnet? Fail the build if yes"
- a quick test on a box with no tools installed
- verifying a firewall change
- watching for a new open port and alerting
- learning what tools do
Common mistakes
Mistakes. No timeout, so the first filtered port hangs the program forever. Sockets that are never closed, until the system runs out. Thousands of threads, which overwhelm your own machine and the target. Treating no answer as closed, when it usually means a firewall. Scanning without permission. Trusting a banner, which any service can set to anything it likes. And keeping no record of what you scanned.
- no timeout: it hangs forever
- sockets never closed
- thousands of threads
- treating "no answer" as "closed"
- scanning without permission
- trusting a banner: it can lie
- no record of what was scanned
Say it like this
In the interview: for each port I open a TCP socket with a timeout and attempt to connect. Success means open, an immediate refusal means closed, and a timeout means filtered. Because the work is almost entirely waiting on the network, I run the attempts concurrently with a thread pool or async I/O. I read a banner from open ports, close every socket, and bound the concurrency so I do not overload the target. Then mention that Nmap adds SYN scans, UDP and version detection.
- "For each port, open a TCP
- socket with a timeout and call
- connect: success means open, refusal closed, a timeout
- filtered. I run attempts
- concurrently with a thread
- pool because the work is waiting on I/O, read banners
- from open ports, and close
- every socket."