python写的udp ping客户端
时间: 2023-11-14 14:24:46 浏览: 47
以下是一个简单的 Python UDP Ping 客户端示例:
```python
import socket
import time
server_ip = '127.0.0.1'
server_port = 12000
timeout = 1 # 超时时间(秒)
max_attempts = 10 # 最大尝试次数
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in range(max_attempts):
message = 'Ping {}'.format(i + 1).encode()
start_time = time.time()
client_socket.sendto(message, (server_ip, server_port))
try:
client_socket.settimeout(timeout)
data, server = client_socket.recvfrom(1024)
elapsed_time = time.time() - start_time
print('Received: {}, Time elapsed: {:.3f}s'.format(data.decode(), elapsed_time))
except socket.timeout:
print('Request timed out')
finally:
print('')
client_socket.close()
```
该程序使用 `socket` 模块创建一个 UDP socket 对象,并在 `for` 循环中向服务器发送多个 Ping 请求。对于每个 Ping 请求,程序记录下当前时间,并在发送请求时将其发送给服务器。然后程序等待服务器响应,如果收到响应,则计算从发送请求到接收响应所经过的时间,并打印出来。如果超时没有收到响应,则打印出 "Request timed out" 消息。程序最后关闭 socket 连接。