1
+ # from requests import get
2
+
3
+ # ip = get('https://api.ipify.org').text
4
+ # print( 'My public IP address is:', ip)
5
+
6
+
7
+ import os
8
+ import socket
9
+ import multiprocessing
10
+ import subprocess
11
+ import os
12
+
13
+
14
+ def pinger (job_q , results_q ):
15
+ """
16
+ Do Ping
17
+ :param job_q:
18
+ :param results_q:
19
+ :return:
20
+ """
21
+ DEVNULL = open (os .devnull , 'w' )
22
+ while True :
23
+
24
+ ip = job_q .get ()
25
+
26
+ if ip is None :
27
+ break
28
+
29
+ try :
30
+ subprocess .check_call (['ping' , '-c1' , ip ],
31
+ stdout = DEVNULL )
32
+ results_q .put (ip )
33
+ except :
34
+ pass
35
+
36
+
37
+ def get_my_ip ():
38
+ """
39
+ Find my IP address
40
+ :return:
41
+ """
42
+ s = socket .socket (socket .AF_INET , socket .SOCK_DGRAM )
43
+ s .connect (("8.8.8.8" , 80 ))
44
+ ip = s .getsockname ()[0 ]
45
+ s .close ()
46
+ return ip
47
+
48
+
49
+ def map_network (pool_size = 255 ):
50
+ """
51
+ Maps the network
52
+ :param pool_size: amount of parallel ping processes
53
+ :return: list of valid ip addresses
54
+ """
55
+
56
+ ip_list = list ()
57
+
58
+ # get my IP and compose a base like 192.168.1.xxx
59
+ ip_parts = get_my_ip ().split ('.' )
60
+ base_ip = ip_parts [0 ] + '.' + ip_parts [1 ] + '.' + ip_parts [2 ] + '.'
61
+
62
+ # prepare the jobs queue
63
+ jobs = multiprocessing .Queue ()
64
+ results = multiprocessing .Queue ()
65
+
66
+ pool = [multiprocessing .Process (target = pinger , args = (jobs , results )) for i in range (pool_size )]
67
+
68
+ for p in pool :
69
+ p .start ()
70
+
71
+ # cue hte ping processes
72
+ for i in range (1 , 255 ):
73
+ jobs .put (base_ip + '{0}' .format (i ))
74
+
75
+ for p in pool :
76
+ jobs .put (None )
77
+
78
+ for p in pool :
79
+ p .join ()
80
+
81
+ # collect he results
82
+ while not results .empty ():
83
+ ip = results .get ()
84
+ ip_list .append (ip )
85
+
86
+ return ip_list
87
+
88
+
89
+ if __name__ == '__main__' :
90
+
91
+ print ('Mapping...' )
92
+ lst = map_network ()
93
+ print (lst )
0 commit comments