Python中未指定的字节长度

Python中未指定的字节长度,python,struct,Python,Struct,我正在为一个P2P应用程序编写一个客户端,协议规范说每个数据包的头应该有一个特定字节长度的字段,如下所示: Version: 1 Byte Type: 1 Byte Length: 2 Bytes And then the data 我有这样的方法来打包和解包标题字段(我认为): packed = struct.pack('cch' , '1' , '1' , 26) unpack('cchs*', data) 这为数据长度为26的数据包构造了一个报头,但是当涉及到解包数据时,我不确定以

我正在为一个P2P应用程序编写一个客户端,协议规范说每个数据包的头应该有一个特定字节长度的字段,如下所示:

Version: 1 Byte 
Type: 1 Byte
Length: 2 Bytes
And then the data
我有这样的方法来打包和解包标题字段(我认为):

packed = struct.pack('cch' , '1' , '1' , 26)
unpack('cchs*', data)
这为数据长度为26的数据包构造了一个报头,但是当涉及到解包数据时,我不确定以后如何获取其余的数据。要解包,我们需要知道所有字段的大小,除非我遗漏了什么?我想要打包数据,我会使用格式指示符“cch26s”,意思是:

1 Byte char
1 Byte char
2 Byte short
26 Byte char array

但是,当我不知道数据包中首先包含多少数据时,如何解包呢

您可以通过检查
len(数据)
来推测要解压缩的字符数

下面是一个帮助器函数,它可以为您执行以下操作:

def unpack(fmt, astr):
    """
    Return struct.unpack(fmt, astr) with the optional single * in fmt replaced with
    the appropriate number, given the length of astr.
    """
    # http://stackoverflow.com/a/7867892/190597
    try:
        return struct.unpack(fmt, astr)
    except struct.error:
        flen = struct.calcsize(fmt.replace('*', ''))
        alen = len(astr)
        idx = fmt.find('*')
        before_char = fmt[idx-1]
        n = (alen-flen)/struct.calcsize(before_char)+1
        fmt = ''.join((fmt[:idx-1], str(n), before_char, fmt[idx+1:]))
        return struct.unpack(fmt, astr)
您可以这样使用它:

packed = struct.pack('cch' , '1' , '1' , 26)
unpack('cchs*', data)

按照描述协议的方式,应该首先解压缩前四个字节,然后提取长度(16位整数)。这将告诉您在第二步中要解压缩多少字节

version, type, length = struct.unpack("cch", packed[:4])
content, = struct.unpack("%ds" % length, packed[4:])
如果一切正常的话。unpack()要求打包的缓冲区包含的数据量与解包的数据量完全相同。另外,检查长度计数中是否包含4个标头字节