Sending C++ uint32_t to Python client through TCP socket.
I have two functions:
void send_int(uint num)
{
num = 255; //Assign to 255 for debug purposes
num = htonl(num);
uint8_t* byte_pointer = reinterpret_cast<uint8_t*>(&num);
for (std::size_t i = 0; i < sizeof(num); ++i)
{
cdbg_print_to_info_channel("%02X ", byte_pointer[i]);
}
ssize_t sent = 0;
const uint8_t* data = reinterpret_cast<const uint8_t*>(&num);
while (sent < ssize_t(sizeof(num)))
{
ssize_t ret = ::send(clientfd, data + sent, sizeof(num) - sent, 0);
if (ret < 0)
{
// TODO
break;
}
sent += ret;
}
cdbg_print_to_info_channel("Sent 255");
}
And:
def receive_int() -> Optional[int]:
breakpoint()
int_data = server.recv(4)
breakpoint()
print(int_data)
if len(int_data) < 4:
print("Error receiving int!")
return None
number = struct.unpack('!I', int_data)[0]
print(number)
return number
Which are designed to simply send and receive a uint32_t from the CPP client to the Python client.
Running locally, this works perfectly. My CPP side prints the following info:
[17063.126393] (mali-cpu-comman) 00
[17063.126409] (mali-cpu-comman) 00
[17063.126416] (mali-cpu-comman) 00
[17063.126423] (mali-cpu-comman) FF
[17063.126432] (mali-cpu-comman) Sent 255
in the send_int function, and the python receive_int function prints:
b'x00x00x00xff'
255
Which are both expected behavior.
The issue arises when I have the cpp client on another machine. The CPP client prints the same info, but the python client prints:
b'x14x01x02x00'
335610368
The behavior is at least consistent, wherein the “wrong” output will be the same every time, not just a random sequence of bytes.
I suspected this was because of endianness, but I am quite sure it is not as the endianness is explicit for both instances, but I could be wrong somehow.
Could anyone have any idea why this might be an issue?
So far I have tried to change the endianness of the packets I send through CPP client, and how I unpack it on python side. I have attempted to capture the packets and looking at them through Wireshark, but that left me pretty clueless.
26