python 实现ping测试延迟的两种方法
一.python实现ping返回延迟繁琐版
#!/usr/bin/python3.7 #!coding:utf-8 __author__='hsz' __date__='ThuFeb2722:41:15EST2020' importtime importstruct importsocket importselect importsys defchesksum(data): """ 校验 """ n=len(data) m=n%2 sum=0 foriinrange(0,n-m,2): sum+=(data[i])+((data[i+1])<<8)#传入data以每两个字节(十六进制)通过ord转十进制,第一字节在低位,第二个字节在高位 ifm: sum+=(data[-1]) #将高于16位与低16位相加 sum=(sum>>16)+(sum&0xffff) sum+=(sum>>16)#如果还有高于16位,将继续与低16位相加 answer=~sum&0xffff #主机字节序转网络字节序列(参考小端序转大端序) answer=answer>>8|(answer<<8&0xff00) returnanswer ''' 连接套接字,并将数据发送到套接字 ''' defraw_socket(dst_addr,imcp_packet): rawsocket=socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.getprotobyname("icmp")) send_request_ping_time=time.time() #senddatatothesocket rawsocket.sendto(imcp_packet,(dst_addr,80)) returnsend_request_ping_time,rawsocket,dst_addr ''' requestping ''' defrequest_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) returnimcp_packet ''' replyping ''' defreply_ping(send_request_ping_time,rawsocket,data_Sequence,timeout=2): whileTrue: started_select=time.time() what_ready=select.select([rawsocket],[],[],timeout) wait_for_time=(time.time()-started_select) ifwhat_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 ) iftype==0andsequence==data_Sequence: returntime_received-send_request_ping_time timeout=timeout-wait_for_time iftimeout<=0: return-1 ''' 实现ping主机/ip ''' defping(host): data_type=8#ICMPEchoRequest data_code=0#mustbezero data_checksum=0#"...withvalue0substitutedforthisfield..." data_ID=0#Identifier data_Sequence=1#Sequencenumber payload_body=b'abcdefghijklmnopqrstuvwabcdefghi'#data dst_addr=socket.gethostbyname(host)#将主机名转ipv4地址格式,返回以ipv4地址格式的字符串,如果主机名称是ipv4地址,则它将保持不变 print("正在Ping{0}[{1}]具有32字节的数据:".format(host,dst_addr)) foriinrange(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) iftimes>0: print("来自{0}的回复:字节=32时间={1}ms".format(addr,int(times*1000))) time.sleep(0.7) else: print("请求超时。") if__name__=="__main__": #iflen(sys.argv)<2: #sys.exit('Usage:ping.py') ping('www.baidu.com')#sys.argv[1]
二.python实现ping返回延迟简单版本
fromping3importping defping_host(ip): """ 获取节点的延迟的作用 :paramnode: :return: """ ip_address=ip response=ping(ip_address) print(response) ifresponseisnotNone: delay=int(response*1000) print(delay,"延迟") #下面两行新增的 ping_host('www.baidu.com')
以上就是python实现ping测试延迟的两种方法的详细内容,更多关于pythonping测试延迟的资料请关注毛票票其它相关文章!