这个实验类似于要用UDP包来检测网络是否通畅。

服务端

材料里面给了服务器端的代码:

# UDPPingerServer.py 
# We will need the following module to generate randomized lost packets 
import random 
from socket import *  
# Create a UDP socket  
# Notice the use of SOCK_DGRAM for UDP packets 
serverSocket = socket(AF_INET, SOCK_DGRAM) 
# Assign IP address and port number to socket 
serverSocket.bind(('', 12000))  
while True:     
	# Generate random number in the range of 0 to 10 
	rand = random.randint(0, 10)
	# Receive the client packet along with the address it is coming from  
	message, address = serverSocket.recvfrom(1024)
	# Capitalize the message from the client     
	message = message.upper()
    # If rand is less is than 4, we consider the packet lost and do not respond
	if rand < 4:
		continue
    # Otherwise, the server responds         
	serverSocket.sendto(message, address)

服务器的思路非常简单,就是在12000端口监听UDP包,接收到一个包之后,生成一个0到9的随机数,如果随机数小于4,就不返回(故意丢包),否则按原来的内容返回。

客户端

按照实验的要求,向服务器端发送10个包,消息的格式为Ping 次数 时间。设置超时时间为1秒,如果超过1秒没有回复,那么认为丢包。同时需要记录一下从消息发出到恢复收到所用的时间(RTT),结束的时候生成一个报告。

from socket import *
import time
import datetime
# Host
host = ('127.0.0.1', 12000)
# Statistic data
max_rtt = 0.0;
min_rtt = 1.0;
sum_rtt = 0.0;
lost_count = 0.0;
# Create a UDP socket  
# Notice the use of SOCK_DGRAM for UDP packets 
clientSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP and port for socket
clientSocket.bind(('', 10002))
# Set timeout
clientSocket.settimeout(1)
for x in xrange(1,11):
	# Get start timestamp
	start = time.time()
	# Make Ping message
	message = 'Ping ' + str(x) + ' ' + datetime.datetime.fromtimestamp(start).strftime('%H:%M:%S')
	# Send message
	clientSocket.sendto(message, host)
	try:
		message, address = clientSocket.recvfrom(1024)
		# Get end timestamp
		end = time.time()
		# Caculate RTT
		rtt = end - start
		# Count statis
		max_rtt = max(max_rtt, rtt)
		min_rtt = min(min_rtt, rtt)
		sum_rtt += rtt
		print message + " RTT =", rtt
	except timeout:
		# Timeout
		lost_count += 1.0
		print 'Request timed out'
# Report
print "maximum RTT = " + str(max_rtt) + ", minimum RTT = " + str(min_rtt) + ", average RTT = " + str(sum_rtt/(10-lost_count))
print "Sent = 10, Reciced = " + str(10-lost_count) + ", Lost = " + str(lost_count) + ", Lost rate = " + str(lost_count*10) + "%"

用虚拟机向本机发送结果如下: