python写的udp ping
时间: 2023-11-14 22:12:42 浏览: 125
下面是一个简单的Python UDP ping示例:
```python
import socket
import time
server_address = ('localhost', 12000)
ping_message = 'Ping'.encode('utf-8')
timeout = 1.0 # seconds
# create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# set timeout
sock.settimeout(timeout)
for i in range(10):
# send ping message
start_time = time.time()
sock.sendto(ping_message, server_address)
# receive response
try:
data, server = sock.recvfrom(1024)
end_time = time.time()
print('Received response from {}: time={} ms'.format(server[0], int((end_time - start_time) * 1000)))
except socket.timeout:
print('Request timed out')
```
在这个例子中,我们使用了Python的`socket`模块来创建一个UDP socket,并使用`settimeout`方法设置了1秒的超时时间。我们循环发送10个ping消息,并等待接收响应。如果在超时时间内没有收到响应,就会打印“Request timed out”的消息。如果收到响应,就会打印“Received response from <服务器地址>: time=<响应时间> ms”的消息。
阅读全文