当前位置:主页 > 软件编程 > Python代码 >

使用python编写udp协议的ping程序方法

时间:2021-08-30 10:02:15 | 栏目:Python代码 | 点击:

服务器端

import random 
from socket import * 
serverSocket = socket(AF_INET, SOCK_DGRAM)#建立udp协议的socket连接 
serverSocket.bind(('', 12000)) 
while True: 
 rand = random.randint(0, 10)#生成随机数,模拟udp环境下的丢包 
 message, address = serverSocket.recvfrom(1024)#接收客户端发送的信息,应该传送ip地址比较好 
 message = message.upper() 
 if rand < 4: continue#如果随机数字小于4那么就模拟丢包,不进行回复 
 serverSocket.sendto(message, address) 

客户端

from socket import * 
import time 
HOST = 'localhost' 
PORT = 12000 
clientSocket = socket(AF_INET, SOCK_DGRAM)#使用udp协议 
clientSocket.bind(('', 6000))#绑定端口6000, 也可以不绑定 
 
for i in range(0,10):#发出十次ping 
 try: 
  start_time = time.time()#从发出报文开始计时 
  clientSocket.sendto('A',(HOST, PORT))#发送报文给服务器 
  clientSocket.settimeout(1.0)#设置socket等待时间 
  message, address = clientSocket.recvfrom(1024)#recvfrom设置了一秒的时间限制 
  end_time = time.time()#结束时间 
  print "Ping %d %f"%(i, end_time-start_time)#得到ttl,并显示出来 
 except timeout:#如果超过时间,抛出一个timeout的错误 
  print "Resquest time out" 

您可能感兴趣的文章:

相关文章