开发者

Reading UDP Packets

开发者 https://www.devze.com 2022-12-24 21:51 出处:网络
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:

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


An unsigned int32 is 4 bytes long, so you have to feed 4 bytes into struct.unpack.

Replace

mybytes = data[16:19]

with

mybytes = data[16:20]

(right number is the first byte not included, i.e. range(16,19) = [16,17,18]) and you should be good to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号