我在解析UDP数据包时遇到了一些麻烦 . 我收到数据包并将数据和发件人地址存储在变量'data'和'addr'中:
data,addr = UDPSock.recvfrom(buf)
这将数据解析为字符串,我现在无法转换为字节 . 我知道数据报包的结构总共28个字节,而我试图获取的数据是以字节17:28为单位 .
我试过这样做:
mybytes = data[16:19]
print struct.unpack('>I', mybytes)
--> struct.error: unpack str size does not match format
还有这个:
response = (0, 0, data[16], data[17], 6)
bytes = array('B', response[:-1])
print struct.unpack('>I', bytes)
--> TypeError: Type not compatible with array type
还有这个:
print "\nData byte 17:", str.encode(data[17])
--> UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128)
更具体地说,我想解析我认为的unsigned int . 而现在我不确定下一步该尝试什么 . 我对Python中的套接字和字节转换完全不熟悉,所以任何建议都会有所帮助:)
谢谢,托马斯
1 回答
无符号int32长度为4个字节,因此必须将4个字节输入
struct.unpack
.更换
同
(正确的数字是不包括的第一个字节,即范围(16,19)= [16,17,18]),你应该好好去 .