簡體   English   中英

Python 3 垃圾數據放入struct.unpack

[英]Python 3 garbage data into the struct.unpack

我正在嘗試使用 Python 3 通過套接字發送和接收消息。

BUFFER_SIZE = 1024
# Create message
MLI = struct.pack("!I", len(MESSAGE))
MLI_MESSAGE = MLI + str.encode(MESSAGE)

收到消息時:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MLI_MESSAGE)
print ("Sent data: ‘", MESSAGE, "’")
# Receive MLI from response (you might want to add some timeout handling as well
resp = s.recv(BUFFER_SIZE)
resp = struct.unpack("!I", resp)[0]
print(resp)

resp

b'\x00\t\xeb\x07\xdf\x01\x00\xdf\x02\x010'

我收到了那個錯誤:

struct.error: unpack requires a buffer of 4 bytes

我認為它與\t resp相關,但我不確定。 如何刪除該\t字符以及如何解決該問題?

您基本上是在嘗試執行以下操作(已刪除套接字):

1 import struct
2 
3 msg = "foobar"
4 mli = struct.pack("!I", len(msg))
5 mli_msg = mli + str.encode(msg)
6 
7 len = struct.unpack("!I", mli_msg)[0]
8 print(len)

第 7 行中長度的提取將失敗,因為您將整個 mli_msg 作為解包的參數,而不僅僅是 len 的預期 4 個字節。 相反,您應該這樣做:

7 len = struct.unpack("!I", mli_msg[:4])[0] 

除此之外,首先獲取消息的長度然后將消息轉換為字節是錯誤的。 第一個采用字符數,而后者采用字節數,當涉及非 ASCII 字符時,字節數會有所不同 - 檢查len("ü")len(str.encode("ü")) 您需要首先將消息轉換為字節,然后獲取長度以為您發送的內容提供正確的字節長度。

4 encoded_msg = str.encode(msg)
5 mli_msg = struct.pack("!I", len(encoded_msg))  + encoded_msg

!I的解釋:

  • ! 表示大端 alignment
  • I表示無符號 integer 類型,占用 4 個字節。

變量resp值為b'\x00\t\xeb\x07\xdf\x01\x00\xdf\x02\x010' ,長度超過4。

您可以截取 4 個字節進行解析,如下所示。

import struct

resp = b'\x00\t\xeb\x07\xdf\x01\x00\xdf\x02\x010'
print(struct.unpack("!I", resp[:4])[0])

# 649991

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM