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

2
  • Are you performing normal XML-RPC? Is there any reason why you can't use xmlrpclib? Commented Oct 29, 2014 at 11:42
  • It is custom XMLRPC, encrypted and zlibbed. I should support its protocol as is Commented Oct 29, 2014 at 12:09

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Strange, but the header is always 0
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 @

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.