SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · PYTHON · 39 OF 229

Build a Port Scanner in Python, Step by Step

Write a working TCP connect scanner in about 40 lines of Python to understand what Nmap does: one connection attempt with a timeout, a loop over ports, threads for speed, reading service banners, and command-line options. Tested on a lab machine, it checked 10,000 ports in 1.15 seconds and found 3 open. Then why timeouts dominate real scans, and the rules for using it.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • connect with a timeout
  • a thread pool for speed
  • banners
  • timeouts decide scan time
  • your own lab only

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.

check one port
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.

scan a range
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]

Banners

An open port is more useful when you know what is behind it. Many services send a greeting as soon as you connect: SSH announces its version, mail servers say hello. This function connects, reads up to eighty bytes and returns them as text, or an empty string if nothing arrives. Web servers stay silent until asked, so they show no banner. Real scanners send protocol-specific probes to draw a reply out of quiet services.

grab a banner
def banner(host, port, timeout):
    try:
        with socket.create_connection(
                (host, port), timeout) as s:
            s.settimeout(timeout)
            data = s.recv(80)
            return data.decode(
                errors="replace").strip()
    except OSError:
        return ""

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.

the command-line wrapper
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.

our run, on loopback
$ 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.

the arithmetic of timeouts
  • 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.

Limits of this version
  • 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.

Use it responsibly
  • 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.

Real uses
  • 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1How does a TCP connect scan work in code?

For each port, create a TCP socket, set a timeout and call connect (or connect_ex). A successful connection means the port is open, an immediate connection-refused error means closed, and a timeout means the probe was dropped, typically by a firewall. The socket is then closed.

Q2Why use threads or async I/O for a port scanner?

Scanning is I/O-bound: nearly all the time is spent waiting for replies or timeouts. Running many attempts concurrently lets those waits overlap, so total time is close to the longest wait rather than the sum of all of them.

Q3What determines how long a port scan takes?

Mostly timeouts on filtered ports. Closed ports answer immediately, but a filtered port costs the full timeout per attempt, so scan time is roughly filtered ports multiplied by the timeout, divided by the concurrency.

Q4What is banner grabbing?

Connecting to an open port and reading the first bytes the service sends, which often include its name and version (SSH, SMTP, FTP). Quiet protocols such as HTTP need a request first. Banners are hints and can be changed or faked by the server.

Q5How can a connect scan tell closed from filtered?

By the result: connection refused (an RST came back) means closed, while a timeout or certain ICMP errors mean filtered. A simple scanner that only checks for success treats both as not open, losing that distinction.

Q6What does Nmap do that a simple scanner does not?

Half-open SYN scans, UDP scanning, service and version detection with protocol probes, OS fingerprinting, adaptive timing and retransmission, a scripting engine, and multiple output formats, all tuned over many years.

Q7Why must sockets be closed and concurrency limited?

Unclosed sockets exhaust file descriptors and leave half-finished connections; unlimited concurrency can exhaust local resources, trigger rate limits or overwhelm fragile targets. A bounded pool and a finally block keep the scan stable and polite.

Q8When would you write your own port check instead of using Nmap?

For small, embedded checks: a CI step that fails if a sensitive port is reachable, a test on a host where only Python is available, verification of a firewall change, or a monitor that alerts on a newly open port.