我试图为类创建一个ICMP Pinger,但是当我尝试编译它时会出现此错误。我不确定还能做什么,大部分代码都是我教科书中的骨架代码,所以我不完全确定会出现什么问题。
编译此代码时
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(str[count+1])) * 256 + ord(str(str[count]))
csum = csum + thisVal
csum = csum & 0xffffffff
count = count + 2
if countTo < len(str):
csum = csum + ord(str[leb(str) - 1])
csum = csum & 0xffffffff
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
andswer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def recieveOnePing(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."
timeRecieved = time.time()
recPacket, addr = mySocket.recvfrom(1024)
icmph = recPacket[20:28]
type, code, checksum, pID, sq = struct.unpack("bbHHh", icmph)
print ("The header received in the ICMP reply is ",type, code, checksum, pID, sq)
if pID == ID:
bytesinDbl = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesinDbl])[0]
rtt=timeReceived - timeSent
print ("RTT is : ")
return rtt
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out"
def sendOnePing(mySocket, destAddr, ID):
myChecksum = 0
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0 , myChecksum, ID, 1)
data = struct.pack("d", time.time())
myChecksum = checksum(header + data)
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
else:
myChecksum = socket.htons(myChecksum)
header = stuct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1))
def doOnePing(destAddr, timeout):
icmp = getprotobyname("icmp")
mySocket = socket(AF_INET, SOCK_STREAM)
myId = os.getpid() & 0xFFFF
sendOnePing(mySocket, destAddr, myID)
delay = recieveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
def ping(host, timeout=1):
dest = gethostbyname(host)
print ("Pinging" + dest + "using Python:")
print ("")
while 1:
delay = doOnePing(dest, timeout)
print(delay)
time.sleep(1)
return delay
ping("www.google.com")
我收到此错误
File "ICMPPinger.py", line 17, in checksum
thisVal = ord(str(str[count+1])) * 256 + ord(str(str[count]))
TypeError: 'bytes' object is not callable
我应该重命名我的变量吗?我不确定这条线应该做什么,当我把它作为
时thisVal = ord(str[count+1]) * 256 + ord(str[count]))
我收到了错误: 文件&#34; ICMPPinger.py&#34;,第17行,在校验和中thisVal = ord(str [count + 1])* 256 + ord(str [count])TypeError:ord()期望字符串长度为1,但是int found
答案 0 :(得分:0)
在def doOnePing()中,您定义了名为myId
的变量,但是您将变量作为名称myID
传递,这就是您获得未定义变量错误的原因。因此,在定义变量时,将myId
替换为myID
,如下所示:
myID = os.getpid() & 0xFFFF