SoFunction
Updated on 2024-07-15

Two ways to implement ping test latency in python

I.python implement ping return delay cumbersome 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 in every two bytes (hexadecimal) through ord to decimal, first byte in low, second byte in high
  if m:
    sum += (data[-1])
  # Add the higher 16 bits to the lower 16 bits
  sum = (sum >> 16) + (sum & 0xffff)
  sum += (sum >> 16) # If there are still bits above 16, it will continue to be added to the lower 16 bits
  answer = ~sum & 0xffff
  # Host byte sequence to network byte sequence (refer to little end sequence to big end sequence)
  answer = answer >> 8 | (answer << 8 & 0xff00)
  return answer

  '''
  Connects to a socket and sends data to the socket
  '''


def raw_socket(dst_addr, imcp_packet):
  rawsocket = (socket.AF_INET, socket.SOCK_RAW, ("icmp"))
  send_request_ping_time = ()
  # send data to the socket
  (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):
  # Packing bytes into binary data
  imcp_packet = ('>BBHHH32s', data_type, data_code, data_checksum, data_ID, data_Sequence, payload_body)
  icmp_chesksum = chesksum(imcp_packet) # Get the checksum
  imcp_packet = ('>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 = ()
    what_ready = ([rawsocket], [], [], timeout)
    wait_for_time = (() - started_select)
    if what_ready[0] == []: # Timeout
      return -1
    time_received = ()
    received_packet, addr = (1024)
    icmpHeader = received_packet[20:28]
    type, code, checksum, packet_id, sequence = (
      ">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

  '''
  Implementing 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 = (host) # Convert hostname to ipv4 address format, returns a string in ipv4 address format, if the hostname is an ipv4 address, it will remain unchanged
  print("in the process of (doing something or happening) Ping {0} [{1}] have 32 byte:".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("come from (a place) {0} repliy: nibbles=32 timing={1}ms".format(addr, int(times * 1000)))
      (0.7)
    else:
      print("Request timeout.")


if __name__ == "__main__":
  # if len() < 2:
  #   ('Usage:  <host>')
  ping('') # [1]

A simple version of python that implements ping return latency.

from ping3 import ping


def ping_host(ip):
  """
  Get the role of the node's delay
  :param node.
  :return.
  """
  ip_address = ip
  response = ping(ip_address)
  print(response)
  if response is not None:
    delay = int(response * 1000)
    print(delay, "Delay")
    # The following two lines have been added


ping_host('')

The above is python realize ping test latency of the two methods of details, more information about python ping test latency please pay attention to my other related articles!