Skip to content

Commit 5068926

Browse files
committed
add comments
1 parent 946ffa9 commit 5068926

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Python/Async-Port-Scanner/scan-ports.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
import sys
44
import ipaddress
55

6+
# Check if the user has provided commandline arguments.
67
if len(sys.argv) < 2:
78
print("Not enough commandline arguments.")
89
sys.exit()
910

11+
# Check if the IP address or website is valid or not.
1012
try:
1113
ipaddress.ip_address(sys.argv[1])
1214
except ValueError:
@@ -20,27 +22,37 @@
2022
else:
2123
target_IP = sys.argv[1]
2224

25+
# create a list to store custom ports.
2326
custom_ports = []
2427
if len(sys.argv) > 2:
2528
custom_ports = sys.argv[2:]
2629

30+
# Method to scan a single port
2731
def scan_port(target_IP, port):
32+
# Create a socket object.
2833
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
34+
35+
# Set default timeout to 1 second.
2936
socket.setdefaulttimeout(1)
3037

38+
# Try to connect the target
3139
result = s.connect_ex((target_IP, port))
3240

41+
# Check if connection was successful
3342
if result == 0:
3443
print(f"Port {port}: \033[92mOPEN\033[0m")
3544
return port
3645

3746
print(f"Port {port}: \033[91mCLOSED\033[0m")
3847
return None
3948

49+
# List to hold open ports.
4050
open_ports = []
4151

52+
# Create a context manager to spawn individual threads for each port.
4253
with concurrent.futures.ThreadPoolExecutor() as executor:
4354

55+
# Check if the users has provided custom ports or not.
4456
if len(custom_ports) == 0:
4557
future_to_port = {
4658
executor.submit(scan_port, target_IP, port): port for port in range(65535)
@@ -50,14 +62,20 @@ def scan_port(target_IP, port):
5062
executor.submit(scan_port, target_IP, int(port)): port for port in custom_ports
5163
}
5264

65+
# Run a loop to collect open ports.
5366
for future in concurrent.futures.as_completed(future_to_port):
67+
# Get the selected port
5468
port = future_to_port[future]
5569
try:
70+
# Check if it a valid port.
5671
open_port = future.result()
5772
except Exception as e:
73+
# Print any errors.
5874
print(f"Exception:{e}")
5975
else:
76+
# Add to the list if it's a valid port.
6077
if open_port is not None:
6178
open_ports.append(open_port)
6279

80+
# Finally print all the open ports.
6381
print(f"Open Ports:{open_ports}")

0 commit comments

Comments
 (0)