python ip scanner range threads

Solutions on MaxInterview for python ip scanner range threads by the best coders in the world

showing results for - "python ip scanner range threads"
Jana
13 Nov 2019
1
2import socket, threading
3
4host = raw_input("Enter an address to scan: ")
5ip = socket.gethostbyname(host)
6threads = []
7open_ports = {}
8
9def try_port(ip, port, delay, open_ports):
10
11    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket.AF_INET, socket.SOCK_STREAM
12    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
13    sock.settimeout(delay)
14    result = sock.connect_ex((ip, port))
15
16    if result == 0:
17        open_ports[port] = 'open'
18        return True
19    else:
20        open_ports[port] = 'closed'
21        return None
22
23def scan_ports(ip, delay):
24
25def scan_ports(ip, delay):
26
27    for port in range(0, 1023):
28        thread = threading.Thread(target=try_port, args=(ip, port, delay, open_ports))
29        threads.append(thread)
30
31    for i in range(0, 1023):
32        threads[i].start()
33
34    for i in range(0, 1023):
35        threads[i].join()
36
37    for i in range (0, 1023):
38        if open_ports[i] == 'open':
39            print '\nport number ' + str(i) + ' is open'
40        if i == 1022:
41            print '\nscan complete!'
42
43if __name__ == "__main__":
44    scan_ports(ip, 3)
45