如何用Python编写一个实现ping命令功能的长尾式小程序?
- 内容介绍
- 相关推荐
本文共计710个文字,预计阅读时间需要3分钟。
ping的原理是发送一个ICMP请求包,然后根据目标地址的响应包来判断是否能够与该主机进行通信。我们使用Python实现,借助Scapy库进行编程。
pythonfrom scapy.all import *import time
def ping(host): # 创建一个ICMP请求包 packet=IP(dst=host) / ICMP()
# 发送ICMP请求包并接收响应 response=sr1(packet, timeout=1, verbose=0)
# 检查是否收到响应 if response: print(f主机{host}响应时间:{response.time - time.time()}秒) else: print(f主机{host}无响应)
测试ping(www.example.com)
ping的原理是发送一个ICMP请求包,然后根据目的地址的应答包来判断是否能够和这个主机进行通信。
我们使用python实现,借助于scapy来进行编写程序。
from scapy.all import * import time,struct,random # 编写ping一个包的函数。 def ping_one(dst = '36.152.44.95',ttl_no = 64,id_no = 345,seq_no = 5): start_time = time.time() # 将时间转换为二进制序列。 time_to_bytes = struct.pack('>d',start_time) # 进行发送ICMP包,发送出去一个,收回来一个。
本文共计710个文字,预计阅读时间需要3分钟。
ping的原理是发送一个ICMP请求包,然后根据目标地址的响应包来判断是否能够与该主机进行通信。我们使用Python实现,借助Scapy库进行编程。
pythonfrom scapy.all import *import time
def ping(host): # 创建一个ICMP请求包 packet=IP(dst=host) / ICMP()
# 发送ICMP请求包并接收响应 response=sr1(packet, timeout=1, verbose=0)
# 检查是否收到响应 if response: print(f主机{host}响应时间:{response.time - time.time()}秒) else: print(f主机{host}无响应)
测试ping(www.example.com)
ping的原理是发送一个ICMP请求包,然后根据目的地址的应答包来判断是否能够和这个主机进行通信。
我们使用python实现,借助于scapy来进行编写程序。
from scapy.all import * import time,struct,random # 编写ping一个包的函数。 def ping_one(dst = '36.152.44.95',ttl_no = 64,id_no = 345,seq_no = 5): start_time = time.time() # 将时间转换为二进制序列。 time_to_bytes = struct.pack('>d',start_time) # 进行发送ICMP包,发送出去一个,收回来一个。

