Monday 15 August 2011

python - unpack requires a string argument of length 24 -



python - unpack requires a string argument of length 24 -

i not sure doing wrong here trying open file, trace1.flow, read header info throw source ip , destination ip dictionaries. done in python running on fedora vm. getting next error:

(secs, nsecs, booted, exporter, mysourceip, mydestinationip) = struct.unpack('iiiiii',mybuf) struct.error: unpack requires string argument of length 24

here code:

import struct import socket #dictionaries uniqsource = {} uniqdestination = {} def int2quad(i): z = struct.pack('!i', i) homecoming 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"

you seem assume file.read raise eoferror on end of file, error raised input() , raw_input(). file.read homecoming string that's shorter requested (possibly empty).

so need check length after reading:

mybuf = myfile.read(24) if len(mybuf) < 24: break

python

No comments:

Post a Comment