Reading UDP Packets

Posted by Thomas Mathiesen on Stack Overflow See other posts from Stack Overflow or by Thomas Mathiesen
Published on 2010-03-23T16:53:09Z Indexed on 2010/03/23 16:53 UTC
Read the original article Hit count: 405

Filed under:
|
|

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)

And 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

© Stack Overflow or respective owner

Related posts about python

Related posts about networking