0

I want to implement socket client in Python. The server expects the first 8 bytes contain total transmission size in bytes. In C client I did it like this:

uint64_t total_size = zsize + sizeof ( uint64_t );
uint8_t* xmlrpc_call = malloc ( total_size );
memcpy ( xmlrpc_call, &total_size, sizeof ( uint64_t ) );
memcpy ( xmlrpc_call + sizeof ( uint64_t ), zbuf, zsize );

Where zsize and zbuff are size and data I want to transmit. In python I create byte array like this:

cmd="<xml>do_reboot</xml>"
result = deflate (bytes(cmd,"iso-8859-1"))
size = len(result)+8

What is the best to fill the header in Python? Without separating value to 8 bytes and copy it in loop

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
pugnator
  • 665
  • 10
  • 27

1 Answers1

1

You could use the struct module, which will pack your data into binary data in the format you want

import struct
# ...your code for deflating and processing data here...

result_size = len(result)
# `@` means use native size, `I` means unsigned int, `s` means char[].
# the encoding for `bytes()` should be changed to whatever you need
to_send = struct.pack("@I{0}s".format(result_size), result_size, bytes(result, "utf-8"))

See also:

Community
  • 1
  • 1
XrXr
  • 2,027
  • 1
  • 14
  • 20
  • Strange, but the header is always 0 – pugnator Oct 29 '14 at 18:41
  • The header is there, you might be looking at the padding, which is 0. when `result` = `"good day"`, `to_send` = `b'\x08\x00\x00\x00good day'`. You can also check using `to_send[0]`. If you want the padding to come before the number, you can use `>` instead of `@` – XrXr Oct 29 '14 at 21:31