1

I have a google protobuf serialized string(its a serialized string), it contains text, mac address and ip address in bytes. I am trying to make a c structure with this string using python c type. If my mac or ip contains consecutive zeroes, it will break the string to be packed in the structure. The bytesarray will be filled with 0.

from ctypes import *


def create_structure(serialized_string):
    msg_length = len(serialized_string)
    print(serialized_string)

    class CommonMessage(Structure):
        _pack_ = 1
        _fields_ = [("sof", c_uint), ("request_id", c_uint), ("interface", c_uint), ("msg_type", c_uint),
                    ("response", c_uint), ("data_len", c_int), ("data", c_char * msg_length)]

    sof = 4293844428
    common_msg = CommonMessage(sof, 123456,
                               11122946,
                               6000, 0, msg_length,
                               serialized_string
                               )
    print(bytearray(common_msg))


breaking_string = b'\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2'

create_structure(breaking_string)

This will work perfectly if there are no consecutive zeroes in the char array.

Thomas John
  • 2,138
  • 2
  • 22
  • 38

1 Answers1

0

ctypes has some "helpful" conversions that don't help in this case. If you use the c_ubyte type for the array it won't use the conversion. It won't accept a byte string as an initializer, but you can construct a c_ubyte array:

from ctypes import *

def create_structure(serialized_string):
    msg_length = len(serialized_string)
    print(serialized_string)

    class CommonMessage(Structure):
        _pack_ = 1
        _fields_ = [("sof", c_uint), ("request_id", c_uint), ("interface", c_uint), ("msg_type", c_uint),
                    ("response", c_uint), ("data_len", c_int), ("data", c_ubyte * msg_length)]

    sof = 4293844428
    common_msg = CommonMessage(sof, 123456,
                               11122946,
                               6000, 0, msg_length,
                               (c_ubyte*msg_length)(*serialized_string)
                               )
    print(bytearray(common_msg))


breaking_string = b'\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2'

create_structure(breaking_string)

Output:

b'\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2'
bytearray(b'\xcc\xdd\xee\xff@\xe2\x01\x00\x02\xb9\xa9\x00p\x17\x00\x00\x00\x00\x00\x00b\x00\x00\x00\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2')
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251