作业描述
《计算机网络:自顶向下方法》中第四章末尾给出了此编程作业的简单描述:
ping是一种流行的网络应用程序,用于测试位于远程的某个特定的主机是否开机和可达。它也经常用于测量客户主机和目标主机之间的时延。
他的工作过程是:向目标主机发送ICMP“回显请求”分组(即ping分组),并且侦听ICMP“回显响应”应答(即pong分组)。ping测量RTT,记录分组丢失和计算多个ping-pong交换(往返时间的最小,平均,最大和标准差)的统计汇总。
在本实验中,你将用Python语言编写自己的ping应用程序。你的应用程序将使用ICMP。但为了保持程序的简单,你将不完全遵循RFC 1739中的官方规范。注意到你将仅需要写该程序的客户程序,因为服务器侧所需的功能构建在几乎所有的操作系统中。你能够在Web站点 找到本作业的全面细节,以及该Python代码的重要片段。
Python代码框架:
注意:只是框架,实现代码中有很多改动,而且这里是用的python2,但是现在谁还用py2啊?
from socket import *
import os
import sys
import struct
import time
import select
import binascii
ICMP_ECHO_REQUEST = 8
def checksum(str):
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
csum = csum + thisVal
csum = csum & 0xffffffffL
count = count + 2
if countTo < len(str):
csum = csum + ord(str[len(str) - 1])
csum = csum & 0xffffffffL
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return "Request timed out."
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
#Fill in start
#Fetch the ICMP header from the IP packet
#Fill in end
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out."
def sendOnePing(mySocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum.
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
#Convert 16-bit integers from host to network byte order.
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str
#Both LISTS and TUPLES consist of a number of objects
#which can be referenced by their position number within the object
def doOnePing(destAddr, timeout):
icmp = socket.getprotobyname("icmp")
#SOCK_RAW is a powerful socket type. For more details see: http://sock-raw.org/papers/sock_raw
#Fill in start
#Create Socket here
#Fill in end
myID = os.getpid() & 0xFFFF #Return the current process i
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
def ping(host, timeout=1):
#timeout=1 means: If one second goes by without a reply from the server,
#the client assumes that either the client’s ping or the server’s pong is lost
dest = socket.gethostbyname(host)
print "Pinging " + dest + " using Python:"
print ""
#Send ping requests to a server separated by approximately one second
while 1 :
delay = doOnePing(dest, timeout)
print delay
time.sleep(1)# one second
return delay
ping("www.poly.edu")
Python代码实现(基于ICMP协议编写的Ping程序):
import socket
import os
import sys
import struct
import time
import select
import binascii
ICMP_ECHO_REQUEST = 8
# 计算checksum
def checksum(str):
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = str[count+1] * 256 + str[count]
csum = csum + thisVal
csum = csum & 0xffffffff
count = count + 2
if countTo < len(str):
csum = csum + str[len(str) - 1].decode()
csum = csum & 0xffffffff
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
# 客户机接收服务器的Pong响应
def receiveOnePing(mySocket, ID, sequence, destAddr, timeout):
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return "Request timed out."
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
#Fetch the ICMP header from the IP packet
#获得ICMP_ECHO_REPLY结构体,取出校验和checksum、序列号ID、生存时间TTL
#获得ICMP_ECHO_REPLY结构体,取出校验和checksum、序列号ID、生存时间TTL
header = recPacket[20: 28]
type,code,checksum,packetID,sequence = struct.unpack("!bbHHh", header)
if type == 0 and packetID == ID:
byte_in_double = struct.calcsize("!d")
timeSent = struct.unpack("!d", recPacket[28: 28 + byte_in_double])[0]
delay = timeReceived - timeSent
ttl = ord(struct.unpack("!c", recPacket[8:9])[0].decode())
return (delay, ttl, byte_in_double)
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out."
# 客户机向服务器发送一个Ping报文
def sendOnePing(mySocket, ID, sequence, destAddr):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum.
# struct -- Interpret strings as packed binary data
header = struct.pack("!bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, sequence)
data = struct.pack("!d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
#if sys.platform == 'darwin':
# myChecksum = socket.htons(myChecksum) & 0xffff
# Convert 16-bit integers from host to network byte order.
#else:
# myChecksum = socket.htons(myChecksum)
header = struct.pack("!bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, sequence)
packet = header + data
# AF_INET address must be tuple, not str
#Both LISTS and TUPLES consist of a number of objects
#which can be referenced by their position number within the object
mySocket.sendto(packet, (destAddr, 1))
# 客户机发出一次Ping请求
def doOnePing(destAddr, ID, sequence, timeout):
icmp = socket.getprotobyname("icmp")
#SOCK_RAW is a powerful socket type. For more details see: http://sock-raw.org/papers/sock_raw
#SOCK_RAW:原始套接字
#普通的套接字无法处理**ICMP**、IGMP等网络报文,而**SOCK_RAW**可以;
#Create Socket here
#创建一个套接字,使得客户机和服务器相关联
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
# 向服务器发送一个Ping报文
sendOnePing(mySocket, ID, sequence, destAddr)
# 从服务器接收一个Pong报文
delay = receiveOnePing(mySocket, ID, sequence, destAddr, timeout)
mySocket.close()
return delay
# 要调用的主体程序
def ping(host, timeout=1):
# timeout=1 means: If one second goes by without a reply from the server,
# the client assumes that either the client’s ping or the server’s pong is lost
dest = socket.gethostbyname(host)
print("Pinging " + dest + " using Python:")
print("")
# Send ping requests to a server separated by approximately one second
myID = os.getpid() & 0xFFFF
loss = 0
for i in range(4): # 向服务器发出4次Ping请求
result = doOnePing(dest, myID, i, timeout)
if not result:
print("第"+str(i)+"次Ping请求超时(>1s)")# 响应超时,丢包数量+1
loss += 1
else:
delay = int(result[0]*1000)
ttl = result[1]
bytes = result[2]
print("第"+str(i)+"次Ping请求成功:")
print("收到的Pong响应消息:"+dest+":byte(s)="+str(bytes)+"delay="+str(delay)+"ms TTL="+str(ttl))
time.sleep(1)
print("发送次数:"+str(4)+" 发送成功次数:"+str(4-loss)+" 丢包次数:"+str(loss))
'''
原始的请求代码(客户机发出无数次Ping请求,而且没有考虑请求成功与否)
while 1 :
delay = doOnePing(dest, timeout)
print delay
time.sleep(1)# one second
return delay
'''
return
ping("www.baidu.com")
运行效果:
这里ping的是百度,也可以自己换个url试试。
可选练习【待完成】
- 目前,程序计算每个包的往返时间,并逐个打印出来。修改此命令以符合标准ping程序的工作方式。你需要在所有ping完成后,报告最小,最大和平均RTT,以及数据包丢失率(百分比)。
- 你的程序只能检测ICMP超时。修改Ping程序,解析ICMP响应错误代码,并向用户显示相应的错误结果。ICMP响应错误码示例有0:目标网络无法到达可达,1:目标主机无法到达。
介绍:因特网控制报文协议(ICMP,Internet Control Message Protocol)
我的理解就是:
比如上面写的这个ping程序 或者 cmd里面的ping程序,都是向一个服务器发出ping回显请求(比如请求一个网页),然后收到pong回显响应,响应消息就是一堆的东西打印出来(比如丢包率、RTT这些)。
ICMP Header
ICMP报头从IP报头的第160位开始(使用IP选项除外)。
- Type - ICMP 类型。
- Code - 给定ICMP类型的子类型。
- Checksum - 用ICMP头和ICMP数据计算出来的错误校验和,计算时将本字段值作为0输入。
- ID - ID值,应在回显的情况下返回。
- Sequence - 序列值,应在回显的情况下返回。
Echo Request(回显请求:ping)
回显请求是一个ICMP消息,其数据将在回显(“pong”)中接收回来。主机必须响应所有回显请求,并在回显响应中包含从请求消息中接收到的所有数据。
- Type必须置为8。
- Code必须置为0。
- 客户机可以使用ID值和Sequence值来匹配响应和请求。实际上,大多数Linux系统都为每一个ping进程使用唯一ID值,Sequence值在该进程中是不断递增的。Windows使用一个固定ID值,该标识符在Windows版本之间变化,并且只在启动时重置Sequence值。
- 接收到的回显响应必须完全包含回显请求中的数据。
Echo Reply(回显响应:pong)
回显响应是用于响应回显请求而生成的ICMP消息,所有主机和路由器都必须实现该功能。
- Type和Code必须置为0。
- ID值和Sequence值用于让客户端匹配回显请求和回显响应。
- 回显响应必须完全包含接收到的回显请求中的数据。
参考资料:
https://github.com/moranzcw/Computer-Networking-A-Top-Down-Approach-NOTES