File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import sys
2+ import socket
3+ from datetime import datetime
4+ import threading
5+
6+
7+ # Function to scan a port
8+
9+
10+ def scan_port (target , port ):
11+ try :
12+ sock = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
13+ sock .settimeout (1 )
14+ result = sock .connect_ex (
15+ (target , port )
16+ ) # error indicator - if the connection is successful, it returns 0; otherwise, it returns an error code
17+ if result == 0 :
18+ print (f"Port { port } is open" )
19+ sock .close ()
20+ except Exception as e :
21+ print (f"Error scanning port { port } : { e } " )
22+
23+
24+ # Main function to scan ports on a given IP address (argument validation and target definition)
25+
26+
27+ def main ():
28+ if len (sys .argv ) != 2 :
29+ print ("Usage: python scanner.py <IP_ADDRESS>" )
30+ sys .exit (1 )
31+
32+ target = sys .argv [1 ]
33+ print (f"Scanning target: { target } " )
34+
35+ # Record the start time of the scan
36+
37+ start_time = datetime .now ()
38+
39+ # Create threads for scanning ports 1 to 65535
40+
41+ threads = []
42+ for port in range (1 , 65536 ):
43+ thread = threading .Thread (target = scan_port , args = (target , port ))
44+ threads .append (thread )
45+ thread .start ()
46+
47+ # Wait for all threads to complete
48+
49+ for thread in threads :
50+ thread .join ()
51+
52+ # Record the end time of the scan and calculate the duration
53+
54+ end_time = datetime .now ()
55+ duration = end_time - start_time
56+ print (f"Scanning completed in: { duration } " )
57+
58+
59+ if __name__ == "__main__" :
60+ main ()
You can’t perform that action at this time.
0 commit comments