读取UDP数据包

3

我在分析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

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)

更具体地说,我想解析我认为是无符号整数的内容。现在我不确定下一步该尝试什么。我对Python中的套接字和字节转换完全陌生,所以任何建议都会有所帮助:)谢谢,Thomas
1个回答

3
一个无符号的int32类型长度为4个字节,所以你需要向struct.unpack中输入4个字节。

替换:

mybytes = data[16:19]

使用

mybytes = data[16:20]

(右侧数字表示第一个字节不包括在内,即range(16,19) = [16,17,18]),按照此格式进行设置即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接