2012-03-22 101 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')