读取UDP数据包
我在解析 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)
更具体地说,我想解析我认为是无符号整数的内容。现在我不知道下一步该尝试什么。我对 Python 中的套接字和字节转换完全陌生,所以任何建议都会有帮助:)
谢谢, 托马斯
I am having some trouble dissecting a UDP packet. I am receiving the packets and storing the data and sender-address in variables 'data' and 'addr' with:
data,addr = UDPSock.recvfrom(buf)
This parses the data as a string, that I am now unable to turn into bytes. I know the structure of the datagram packet which is a total of 28 bytes, and that the data I am trying to get out is in bytes 17:28.
I have tried doing this:
mybytes = data[16:19]
print struct.unpack('>I', mybytes)
--> struct.error: unpack str size does not match format
And this:
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
And this:
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)
More specifically I want to parse what I think is an unsigned int. And now I am not sure what to try next. I am completely new to sockets and byte-conversions in Python, so any advice would be helpful :)
Thanks,
Thomas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
unsigned int32 的长度为 4 个字节,因此您必须将 4 个字节输入到 struct.unpack 中。
替换
为
(正确的数字是不包括的第一个字节,即范围(16,19)= [16,17,18]),你应该可以开始了。
An unsigned int32 is 4 bytes long, so you have to feed 4 bytes into
struct.unpack
.Replace
with
(right number is the first byte not included, i.e. range(16,19) = [16,17,18]) and you should be good to go.