实验:套接字编程作业5:ICMP ping
源代码如下:
# -*- coding: utf-8 -*-
"""
SAFA_LIYT
"""
import socket
import os
import sys
import struct
import time
import select
import binasciiICMP_ECHO_REQUEST = 8# 计算checksum
def checksum(str):csum = 0countTo = (len(str) / 2) * 2count = 0while count < countTo:thisVal = str[count+1] * 256 + str[count]csum = csum + thisValcsum = csum & 0xffffffffcount = count + 2if countTo < len(str):csum = csum + str[len(str) - 1].decode()csum = csum & 0xffffffffcsum = (csum >> 16) + (csum & 0xffff)csum = csum + (csum >> 16)answer = ~csumanswer = answer & 0xffffanswer = answer >> 8 | (answer << 8 & 0xff00)return answer# 客户机接收服务器的Pong响应
def receiveOnePing(mySocket, ID, sequence, destAddr, timeout):timeLeft = timeoutwhile 1:startedSelect = time.time()whatReady = select.select([mySocket], [], [], timeLeft)howLongInSelect = (time.time() - startedSelect)if whatReady[0] == []: # Timeoutreturn "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、生存时间TTLheader = 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 - timeSentttl = ord(struct.unpack("!c", recPacket[8:9])[0].decode())return (delay, ttl, byte_in_double)timeLeft = timeLeft - howLongInSelectif 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 dataheader = 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 objectmySocket.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 lostdest = socket.gethostbyname(host)print("Pinging " + dest + " using Python:")print("")# Send ping requests to a server separated by approximately one secondmyID = os.getpid() & 0xFFFFloss = 0for i in range(10): # 向服务器发出4次Ping请求result = doOnePing(dest, myID, i, timeout)if not result:print("第"+str(i)+"次Ping请求超时(>1s)")# 响应超时,丢包数量+1loss += 1else: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(10)+" 发送成功次数:"+str(10-loss)+" 丢包次数:"+str(loss))return
ping("www.baidu.com")
最短路径
步骤 | N | D(t)p(t) | D(u)p(u) | D(v)p(v) | D(w)p(w) | D(y)p(y) | D(z)p(z) |
0 | X | -- | -- | 3,x | 6,x | 6,x | -- |
1 | Xv | 7,v | 6,v | 3,x | 6,x | 4,v | -- |
2 | Xvy | 7,v | 6,v | 3,x | 6,x | 4,v | 18,y |
3 | Xvyu | 7,v | 6,v | 3,x | 6,x | 4,v | 18,y |
4 | Xvyut | 7,v | 6,v | 3,x | 6,x | 4,v | 12,t |
5 | Xvyut |