unpack需要长度为24的字符串参数

时间:2014-10-31 01:15:49

标签: python

我不确定我在这里做错了什么但是我正在尝试打开一个文件trace1.flow,读取头信息然后将源IP和目标IP放入词典。这是在Fedora VM上运行的Python中完成的。我收到以下错误:

(secs, nsecs, booted, exporter, mySourceIP, myDestinationIP) = struct.unpack('IIIIII',myBuf)
struct.error: unpack requires a string argument of length 24

这是我的代码:

import struct
import socket


#Dictionaries
uniqSource = {}
uniqDestination = {}

def int2quad(i):
        z = struct.pack('!I', i)
        return socket.inet_ntoa(z)


myFile = open('trace1.flow')
myBuf = myFile.read(8)

(magic, endian, version, headerLen) = struct.unpack('HBBI', myBuf)
print "Magic: ", hex(magic), "Endian: ", endian, "Version: ", version, "Header Length: ", headerLen
myFile.read(headerLen - 8)

try:
        while(True):
                myBuf = myFile.read(24)
                (secs, nsecs, booted, exporter, mySourceIP, myDestinationIP) = struct.unpack('IIIIII',myBuf)
                mySourceIP = int2quad(mySourceIP)
                myDestinationIP = int2quad(myDestinationIP)

                if mySourceIP not in uniqSource:
                        uniqSource[mySourceIP] = 1
                else:
                        uniqSource[mySourceIP] += 1

                if myDestinationIP not in uniqDestination:
                        uniqDestination[myDestinationIP] = 1
                else:
                        uniqDestination[myDestinationIP] += 1

                myFile.read(40)

except EOFError:
        print "END OF FILE"

2 个答案:

答案 0 :(得分:3)

您似乎认为file.read会在文件末尾引发EOFError,但此错误仅由input()raw_input()引发。 file.read只会返回一个比请求的字符串短的字符串(可能为空)。

所以你需要在阅读后检查长度:

myBuf = myFile.read(24)
if len(myBuf) < 24:
    break

答案 1 :(得分:0)

也许你已经达到文件结尾了。检查myBuf的长度:

len(myBuf)

它可能不到24个字符长。此外,您不需要这些额外的括号,并尝试使用'nI'指定重复类型,如下所示:

secs, nsecs, booted, exporter, mySourceIP, myDestinationIP = struct.unpack('6I',myBuf)