Port scanning basics in Bash Scripting - Time & Space Complexity
When we scan ports using a script, we want to know how long it takes as the number of ports grows.
We ask: How does the time to scan change when we check more ports?
Analyze the time complexity of the following code snippet.
for port in {1..1000}; do
timeout 1 bash -c ">> /dev/tcp/127.0.0.1/$port" 2>/dev/null
if [ $? -eq 0 ]; then
echo "Port $port is open"
fi
done
This script tries to connect to each port from 1 to 1000 on localhost to see if it is open.
- Primary operation: The for-loop that tries to connect to each port one by one.
- How many times: It runs once for every port in the range (e.g., 1000 times).
Each port check takes about the same time, so total time grows as we add more ports.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 connection attempts |
| 100 | 100 connection attempts |
| 1000 | 1000 connection attempts |
Pattern observation: The time grows directly with the number of ports checked.
Time Complexity: O(n)
This means if you double the number of ports, the scanning time roughly doubles.
[X] Wrong: "The script checks all ports at the same time, so time stays the same no matter how many ports."
[OK] Correct: The script checks ports one after another, so more ports mean more time.
Understanding how loops affect time helps you explain script speed clearly and shows you can think about efficiency.
"What if we scanned multiple ports at the same time using background jobs? How would the time complexity change?"