From 2f202448f7bfaad84cc9afc8d140b77a754e4447 Mon Sep 17 00:00:00 2001 From: fly6516 Date: Tue, 7 Jan 2025 14:36:50 +0800 Subject: [PATCH] =?UTF-8?q?feat(ICMP):=20=E6=B7=BB=E5=8A=A0=20ICMP=20?= =?UTF-8?q?=E6=8A=A5=E6=96=87=E7=9A=84=20RTT=20=E8=AE=A1=E7=AE=97=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现了 ICMP 报文的发送和接收 - 添加了 RTT(往返时间)的计算和显示 - 增加了超时处理机制 --- main.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 3d32ce6..4c65e83 100644 --- a/main.py +++ b/main.py @@ -194,11 +194,33 @@ def send_packet(): src_port = 12345 dest_port = int(dest_port) - # 构造报文并发送 + # ICMP报文需要添加 RTT 计算 if packet_type == "ICMP": sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) packet = construct_icmp() - elif packet_type == "UDP": + + # 记录发送时间 + start_time = time.time() + + # 发送ICMP报文 + sock.sendto(packet, (dest_ip, 0)) + + # 接收响应 + sock.settimeout(2) # 设置超时为2秒 + try: + sock.recvfrom(1024) + end_time = time.time() + rtt = (end_time - start_time) * 1000 # 毫秒 + result.set(f"ICMP请求成功,RTT: {rtt:.2f} 毫秒") + except socket.timeout: + result.set("ICMP请求超时") + finally: + sock.close() + + return # 结束函数 + + # 对于其他报文类型(UDP, TCP) + if packet_type == "UDP": sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) packet = construct_udp(src_port, dest_port) elif packet_type == "TCP":