Ich möchte eine variierende Anzahl IPs anpingen. Das mache ich, damit es nicht zu lange dauert, für jede IP in einem separaten Thread. Selbstverständlich mit einem Timeout:
Code: Alles auswählen
def query(ip_list, timeout):
if timeout is None or timeout < 1:
timeout = 1
print timeout
start = time.time()
thread_list = []
for ip in ip_list:
# Eigene Klasse, aber fast identisch im Vergleich zum Original
t = NewThread(fire=True, target=ping.do_one, args=(ip))
thread_list.append(t)
for thread in thread_list:
while thread.is_alive():
time.sleep(0.01)
res = thread.get_return_value()
if res is not None:
print res
print time.time() - start, 'sek hats gedauert'
Das Ergebnis enthält Pings die weit über dem Timeout liegen:
Mein Lösungsansatz:0.05
0.612943544547
0.613242287217
0.613124402899
0.612961207996
0.613132082659
0.612970423708
0.612978487456
0.613151666047
0.612985783228
...
1.07449290544
1.07528276877
1.07451248883
1.07530811198
...
0.38534578888
0.385557366272
0.385355004592
0.385566197997
5.04199981689 sek hats gedauert
Datentypen überprüfen, Formatierungen prüfen, etc. Hatte bisher aber keinen Erfolg.
Dann hab ich mir das ping-modul mal näher angesehen (Auch wenn ich da nicht 100% durchsteige..):
Code: Alles auswählen
def do_one(dest_addr, timeout):
"""
Returns either the delay (in seconds) or none on timeout.
"""
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
raise # raise the original error
my_ID = os.getpid() & 0xFFFF
send_one_ping(my_socket, dest_addr, my_ID)
delay = receive_one_ping(my_socket, my_ID, timeout)
my_socket.close()
return delay
def receive_one_ping(my_socket, ID, timeout):
"""
receive the ping from the socket.
"""
timeLeft = timeout
while True:
startedSelect = time.clock()
whatReady = select.select([my_socket], [], [], timeLeft)
howLongInSelect = (time.clock() - startedSelect)
if whatReady[0] == []: # Timeout
return
timeReceived = time.clock()
recPacket, addr = my_socket.recvfrom(1024)
icmpHeader = recPacket[20:28]
type, code, checksum, packetID, sequence = struct.unpack(
"bbHHh", icmpHeader
)
if packetID == ID:
bytesInDouble = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
return timeReceived - timeSent
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return
Code: Alles auswählen
...
my_ID = os.getpid() & 0xFFFF
....
if packetID == ID:
Oder hat es mit etwas ganz anderem zu tun, was ich hier übersehe?
Ich habe bis jetzt noch nichts weiter ausprobiert, um das mit den Threads zu untermauern, denn wie schon erwähnt: Ich versteh das, was das ping-modul da macht noch nicht so wirklich und denke mir, ich hab hier evtl. mehr Glück, bei Leuten die schon Erfahrung damit haben.
