python 实现ping测试延迟的两种方法

举报
泽宇-Li 发表于 2020/12/10 21:23:58 2020/12/10
【摘要】 一.python实现ping返回延迟繁琐版12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929...

一.python实现ping返回延迟繁琐版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/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):
  """
  校验
  """
  n = len(data)
  m = n % 2
  sum = 0
  for i in range(0, n - m, 2):
    sum += (data[i]) + ((data[i + 1]) << 8) # 传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位
  if m:
    sum += (data[-1])
  # 将高于16位与低16位相加
  sum = (sum >> 16) + (sum & 0xffff)
  sum += (sum >> 16) # 如果还有高于16位,将继续与低16位相加
  answer = ~sum & 0xffff
  # 主机字节序转网络字节序列(参考小端序转大端序)
  answer = answer >> 8 | (answer << 8 & 0xff00)
  return answer
 
  '''
  连接套接字,并将数据发送到套接字
  '''
 
 
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):
  # 把字节打包成二进制数据
  imcp_packet = struct.pack('>BBHHH32s', data_type, data_code, data_checksum, data_ID, data_Sequence, payload_body)
  icmp_chesksum = chesksum(imcp_packet) # 获取校验和
  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
 
  '''
  实现 ping 主机/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) # 将主机名转ipv4地址格式,返回以ipv4地址格式的字符串,如果主机名称是ipv4地址,则它将保持不变
  print("正在 Ping {0} [{1}] 具有 32 字节的数据:".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("来自 {0} 的回复: 字节=32 时间={1}ms".format(addr, int(times * 1000)))
      time.sleep(0.7)
    else:
      print("请求超时。")
 
 
if __name__ == "__main__":
  # if len(sys.argv) < 2:
  #   sys.exit('Usage: ping.py <host>')
  ping('www.baidu.com') # sys.argv[1]

二 .python实现ping返回延迟简单版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from ping3 import ping
 
 
def ping_host(ip):
  """
  获取节点的延迟的作用
  :param node:
  :return:
  """
  ip_address = ip
  response = ping(ip_address)
  print(response)
  if response is not None:
    delay = int(response * 1000)
    print(delay, "延迟")
    # 下面两行新增的
 
 
ping_host('www.baidu.com')
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。