File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ import socket
2+ import itertools
3+
4+ from multiprocessing import Pool
5+
6+
7+ def generate_ip_range (selected_range ):
8+ """
9+ generate an IP address range from each provided node.
10+ for example `10.0.1-10.1-10` will return a generator
11+ object that has IP `10.0.1.1 - 10.0.10.10` in it
12+ """
13+ octets = selected_range .split ("." )
14+ chunks = [map (int , octet .split ("-" )) for octet in octets ]
15+ ranges = [range (c [0 ], c [1 ] + 1 ) if len (c ) == 2 else c for c in chunks ]
16+ for address in itertools .product (* ranges ):
17+ yield "." .join (map (str , address ))
18+
19+
20+ def check_ip_alive (ip ):
21+ """
22+ efficiently check if an IP address is alive or not
23+ by using the socket.gethostbyaddr function
24+ """
25+ def is_valid_ip (ip ):
26+ try :
27+ socket .inet_aton (ip )
28+ return True
29+ except :
30+ return False
31+
32+ try :
33+ if not is_valid_ip (ip ):
34+ return False
35+ else :
36+ return socket .gethostbyaddr (ip )
37+ except socket .herror :
38+ return False
39+
40+
41+ def check_ip_wrapper (generated_ips , limit = 350 ):
42+ """
43+ multiprocess the check_ip_alive function in order
44+ to proces a large amount of IP addresses quickly
45+ """
46+ alive_ips = []
47+ ips_to_use = []
48+ i = 0
49+ proc_pool = Pool (processes = 35 )
50+
51+ for ip in generated_ips :
52+ ips_to_use .append (ip )
53+ i += 1
54+ if i == limit :
55+ break
56+ for ip in ips_to_use :
57+ try :
58+ result = proc_pool .apply_async (check_ip_alive , args = (ip ,)).get ()
59+ if not result :
60+ pass
61+ else :
62+ alive_ips .append (ip )
63+ except Exception :
64+ pass
65+ proc_pool .close ()
66+ return alive_ips
You can’t perform that action at this time.
0 commit comments