0

I'm developing a secure file transfer system with Python and I'm dealing now with the protocol. My idea is to have something like:

[Command:1byte][DataLength:2bytes][Data]

My problem is that I have no idea on how to deal with binary/hex in Python.

Imagine that I send a packet which command (in binary) is 00000001 (1byte). The dataLength = 200 bytes, then, since I have 16bits to store it, I have 0000000011001000. So the header is: 000000010000000011001000. The question is: how to send that "raw", without coding the 0's and 1's with 1byte each?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Short of a learning exercise... what exactly is wrong with all the existing secure transport protocols that have been tried and tested? – Jon Clements Nov 07 '13 at 12:46
  • possible duplicate of [Byte Array in Python](http://stackoverflow.com/questions/7380460/byte-array-in-python) – asthasr Nov 07 '13 at 12:46
  • I doubt that you have to send actual 1s and 0s yourself. Send `str` values representing bytes. `\x00` is `00000000` in binary, `\x01` is `00000001`, etc. – Martijn Pieters Nov 07 '13 at 12:46

1 Answers1

2

You can use the modules struct and array for this as:

>>> from struct import pack, unpack
>>> from array import array
>>>
>>> # byte (unsigned char) + 2 bytes (unsigned short)
>>> header = pack('BH', 0, 15)
>>> # array of 15 null byte, you can also use string
>>> buffer = array('B', '\0' * 15).tostring()
>>>
>>> header
'\x00\x00\x0f\x00'
>>> buffer
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>
>>> header + buffer
'\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>

You should consider of the byte order. Now to unpack that buffer you can do:

>>> package = header + buffer
>>>
>>> package
'\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>
>>> # unpacking the header
>>> unpack('BH', package[:4])
(0, 15)
>>>
>>> # unpacking the payload
>>> array('B', package[4:])
array('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>>
  • I would definitely consider using an explicit byte order when using the `struct` module to send data over a network. in short `struct.pack('>...', ...)` and `struct.unpack('>...', ...)` – SingleNegationElimination Nov 07 '13 at 13:08