2012-03-22 135 views
0

我目前正在试图建立在Python RDP客户端和我碰到一个LEN检查以下问题来了;蟒蛇LEN计算

来源:http://msdn.microsoft.com/en-us/library/cc240836%28v=prot.10%29.aspx

81 2a -> ConnectData::connectPDU length = 298 bytes Since the most significant bit of the first byte (0x81) is set to 1 and the following bit is set to 0, the length is given by the low six bits of the first byte and the second byte. Hence, the value is 0x12a, which is 298 bytes.

这听起来很奇怪。

对于正常LEN检查,我只是使用:struct.pack(">h",len(str(PacketLen)))

但在这种情况下,我真的没有看到上述我如何计算LEN。

任何帮助将不胜感激!

回答

1

只需设置最显著位通过使用位OR:

struct.pack(">H", len(...) | 0x8000) 

你可能要添加一个检查,以确保长度适合14位,即它小于2 ** 14

编辑:根据TokenMacGuy的评论修正。

+0

感谢您的! 我仍然收到错误DOH: struct.error: 'H' 格式要求-32768 <=号<= 32767 任何想法,为什么? – n00bz0r 2012-03-22 17:29:18

+1

因为'h'是有符号的类型,您很可能希望将未签名版,'H' – SingleNegationElimination 2012-03-22 17:38:28

+0

传说,谢谢你们! – n00bz0r 2012-03-22 17:39:49

0

不可与带宽敏感的传输协议打交道时,一个十分罕见的情况。他们基本上是说,如果遵循适合在0范围内的长度 - > 0x7F的,只使用一个字节,否则,您可以选择使用2个字节。 (注意:16,383因此该系统最大的法律价值)

这里有一个简单的例子:

if len <= 0x7F: 
    pkt = struct.pack('B', len) 
elif len <= 0x3FFF: 
    pkt = struct.pack('>h', len | 0x8000) 
else: 
    raise ValueError('length exceeds maxvalue')