[solved] "unpack"? streamed data bit by bit

Hi everybody,

I got a little problem reading some streaming data I recieve via socket. It is about a motion capture system, giving me position and orientation of a tracked body.
The developer of the system published a C++ sample client, that recieves the streamed data from the tracking-application. I had a look at it and tried to “convert” it into python.
At this point, I have to admint, that I am not really a programmer! I don’t know much about Python, and even less about C++. So I am not always sure what I am doing here :eyebrowlift2:

I managed to recieve the data blocks, but they look really messed up.
Nothing special so far:

import socket
import struct
ip = ""
port = 1511
multicastAdd = ""
mreq = struct.pack('4sl', socket.inet_aton(multicastAdd), socket.INADDR_ANY)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
data, addr = s.recvfrom(10240)
print data

But here you can see how the data looks in the C++ sample (only the values are from the data paket, the text is generated by the client), and what I get with python:

For me, it looks kind of encoded. I had a look at the C++ sample, and could not find any hint of “formant convertion” (e.g. host to network). But finally I found an “unpack” function which seems to read the data bit by bit(?). I am not sure how that pointer and reference stuff in C++ is working, and I also have no idea how to convert that to python. I would be really happy, if someone could help me out with this.
Here is a short sample from the unpack function:

void Unpack(char* pData)
    char *ptr = pData;
    printf("Begin Packet
    // message ID
    int MessageID = 0;
    memcpy(&MessageID, ptr, 2); ptr += 2;
    printf("Message ID : %d
", MessageID);
    // size
    int nBytes = 0;
    memcpy(&nBytes, ptr, 2); ptr += 2;
    printf("Byte count : %d
", nBytes);

I would like to attach the complete .cpp, but for some reason the posting rules tell me, that I am not allowed to post attachments. :frowning:

Would be great if anybody got an idea how to handle this! :slight_smile:


Just guessing here but it seems like you need to convert the input stream into ints (judging by the C code) since it looks like python is just printing out the raw bytes as literal chars.

And, you know, the whole big/little-endian thing, network byte order, etc, etc…

Yes that int convertion is what I am trying right now, but still no sucess :-/

You need to unpack data using struct.unpack or similar routine.

In packet MessageID takes 2 bytes.
nBytes takes 2 bytes.
So as I understand it, to get first two values, you’ll need to call struct.unpack(“HH”, …) routine.

ah thank you! I just did not get how that struct.unpack function works.
got my first values out of the data! thanks a lot :slight_smile: