Two Methods for python to Realize ping Test Delay

  • 2021-08-17 00:36:00
  • OfStack

1. python implements ping return delay tedious version


#!/usr/bin/python3.7
# !coding:utf-8
__author__ = 'hsz'
__date__ = 'Thu Feb 27 22:41:15 EST 2020'

import time
import struct
import socket
import select
import sys


def chesksum(data):
  """
   Calibration 
  """
  n = len(data)
  m = n % 2
  sum = 0
  for i in range(0, n - m, 2):
    sum += (data[i]) + ((data[i + 1]) << 8) #  Incoming data Every two bytes ( 106 Binary) through ord Turn 10 Binary system, number 1 Bytes are in the lower order, the first 2 Bytes are in the high order 
  if m:
    sum += (data[-1])
  #  Will be higher than 16 Bit and low 16 Bit addition 
  sum = (sum >> 16) + (sum & 0xffff)
  sum += (sum >> 16) #  If there are still higher than 16 Bit, will continue with the low 16 Bit addition 
  answer = ~sum & 0xffff
  #  Host byte sequence to network byte sequence (refer to small end sequence to large end sequence) 
  answer = answer >> 8 | (answer << 8 & 0xff00)
  return answer

  '''
   Connection socket , And send the data to the socket 
  '''


def raw_socket(dst_addr, imcp_packet):
  rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
  send_request_ping_time = time.time()
  # send data to the socket
  rawsocket.sendto(imcp_packet, (dst_addr, 80))
  return send_request_ping_time, rawsocket, dst_addr

  '''
  request ping
  '''


def request_ping(data_type, data_code, data_checksum, data_ID, data_Sequence, payload_body):
  #  Pack bytes into 2 Binary data 
  imcp_packet = struct.pack('>BBHHH32s', data_type, data_code, data_checksum, data_ID, data_Sequence, payload_body)
  icmp_chesksum = chesksum(imcp_packet) #  Get checksum 
  imcp_packet = struct.pack('>BBHHH32s', data_type, data_code, icmp_chesksum, data_ID, data_Sequence, payload_body)
  return imcp_packet
  '''
  reply ping
  '''


def reply_ping(send_request_ping_time, rawsocket, data_Sequence, timeout=2):
  while True:
    started_select = time.time()
    what_ready = select.select([rawsocket], [], [], timeout)
    wait_for_time = (time.time() - started_select)
    if what_ready[0] == []: # Timeout
      return -1
    time_received = time.time()
    received_packet, addr = rawsocket.recvfrom(1024)
    icmpHeader = received_packet[20:28]
    type, code, checksum, packet_id, sequence = struct.unpack(
      ">BBHHH", icmpHeader
    )
    if type == 0 and sequence == data_Sequence:
      return time_received - send_request_ping_time
    timeout = timeout - wait_for_time
    if timeout <= 0:
      return -1

  '''
   Realization  ping  Host /ip
  '''


def ping(host):
  data_type = 8 # ICMP Echo Request
  data_code = 0 # must be zero
  data_checksum = 0 # "...with value 0 substituted for this field..."
  data_ID = 0 # Identifier
  data_Sequence = 1 # Sequence number
  payload_body = b'abcdefghijklmnopqrstuvwabcdefghi' # data
  dst_addr = socket.gethostbyname(host) #  Transfer host name to ipv4 Address format, returning the ipv4 A string in address format, if the host name is ipv4 Address, it will remain unchanged 
  print(" In the process of  Ping {0} [{1}]  Have  32  Bytes of data :".format(host, dst_addr))
  for i in range(0, 4):
    icmp_packet = request_ping(data_type, data_code, data_checksum, data_ID, data_Sequence + i, payload_body)
    send_request_ping_time, rawsocket, addr = raw_socket(dst_addr, icmp_packet)
    times = reply_ping(send_request_ping_time, rawsocket, data_Sequence + i)
    if times > 0:
      print(" From  {0}  Reply to :  Byte =32  Time ={1}ms".format(addr, int(times * 1000)))
      time.sleep(0.7)
    else:
      print(" The request timed out. ")


if __name__ == "__main__":
  # if len(sys.argv) < 2:
  #   sys.exit('Usage: ping.py <host>')
  ping('www.baidu.com') # sys.argv[1]

2. python Implementation ping Return Delay Simple Version


from ping3 import ping


def ping_host(ip):
  """
   Obtain the effect of delay of nodes 
  :param node:
  :return:
  """
  ip_address = ip
  response = ping(ip_address)
  print(response)
  if response is not None:
    delay = int(response * 1000)
    print(delay, " Delay ")
    #  Added in the following two lines 


ping_host('www.baidu.com')

The above is the python implementation ping test delay two methods of the details, more about python ping test delay information please pay attention to other related articles on this site!


Related articles: