2014-10-31 95 views
0

我不知道我在做什麼錯在這裏,但我試圖打開一個文件,trace1.flow,讀取頭信息,然後將源IP和目標IP丟入字典。這是在運行在Fedora VM上的Python中完成的。我收到以下錯誤:unpack需要一個字符串參數長度爲24

(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" 

回答

3

您似乎認爲file.read將提高EOFError在文件末尾,但這種誤差成爲僅input()raw_input()募集。 file.read將簡單地返回比請求短的字符串(可能爲空)。

所以,你需要閱讀後檢查長度:

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

也許你已停止使用的文件。檢查myBuf的長度:

len(myBuf) 

它可能少於24個字符長。此外,您不需要這些額外的括號,並嘗試使用'nI'指定重複類型,如下所示:

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