使用python编写udp协议的ping程序方法
服务器端
importrandom
fromsocketimport*
serverSocket=socket(AF_INET,SOCK_DGRAM)#建立udp协议的socket连接
serverSocket.bind(('',12000))
whileTrue:
rand=random.randint(0,10)#生成随机数,模拟udp环境下的丢包
message,address=serverSocket.recvfrom(1024)#接收客户端发送的信息,应该传送ip地址比较好
message=message.upper()
ifrand<4:continue#如果随机数字小于4那么就模拟丢包,不进行回复
serverSocket.sendto(message,address)
客户端
fromsocketimport*
importtime
HOST='localhost'
PORT=12000
clientSocket=socket(AF_INET,SOCK_DGRAM)#使用udp协议
clientSocket.bind(('',6000))#绑定端口6000,也可以不绑定
foriinrange(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,并显示出来
excepttimeout:#如果超过时间,抛出一个timeout的错误
print"Resquesttimeout"
以上这篇使用python编写udp协议的ping程序方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。