def receive_ping(my_socket, ID, timeout):
"""
receive the ping from the socket
"""
start_time = timeout
while True:
start_select = time.clock()
# select.select(rlist, wlist, xlist[, timeout])
# wait until ready for read / write / exceptional condition
# The return value is a triple of lists
what_ready = select.select([my_socket], [], [], start_time)
how_long = (time.clock() - start_select)
if what_ready[0] == []: #timeout
return
time_received = time.clock()
# socket.recvfrom(bufsize[, flags])
# The return value is a pair (string, address)
rec_packet, addr = my_socket.recvfrom(1024)
icmp_header = rec_packet[20 : 28]
ip_type, code, checksum, packet_ID, sequence = struct.unpack("bbHHh", icmp_header)
if ip_type != 8 and packet_ID == ID: # ip_type should be 0
byte_in_double = struct.calcsize("d")
time_sent = struct.unpack("d", rec_packet[28 : 28 + byte_in_double])[0]
return time_received - time_sent
start_time = start_time - how_long
if start_time <= 0:
return
评论列表
文章目录