Reputation: 682
I'm working on a server (implemented in Python) client (implemented in C) application. I want to unpack raw bytes received from a C client using struct module at server side (Python).
My C structure (from C client):
typedef struct lokesh{
int command;
union
{
struct{
int data[100];
int ttl[100];
};
struct{
char config[256];
};
};
} mystructdata;
Unpacking at server side (Python):-
import struct
data,address=socket.recvfrom(1024)
result=struct.unpack('<i 2048s',data)
print(result[0])
But I'm getting an error :-
struct.error: unpack require object of size 2052
I think problem is in my unpack method's format string '<i 2048s'
argument.
Edit :-
now, i have replaced format string
'<i 2048s'
with format string'<i 256s'
Upvotes: 0
Views: 2175
Reputation: 169
Lokesh, I'm not a python expert, but it looks to me like you're telling python's struct that you have:
(based on http://docs.python.org/2/library/struct.html#format-characters)
Looking at your C struct definition, that's not what you have at all. You have:
Now, without looking at the C code which pushes the struct onto the wire, it's difficult to know about the endianness of integers (network byte order is big-endian). But that aside, your data specification to struct looks wrong.
I'm guessing that the interpretation of the union in the C struct will depend on the contents of command. As such, it seems like you'll need to examine command first off, then come up with an appropriate format string for struct based on that. Note that in the data/ttl case you may trip over struct padding issues since it's possible that the compiler on the client side may decide to insert some padding between the data and ttl arrays in order to satisfy alignment requirements, etc.
Upvotes: 2
Reputation: 1124718
There are two problems:
.recvfrom()
returns a tuple of (data, address)
, you need to pass just the data to struct.unpack()
.
You are reading only up to 1024 bytes from the socket, but the unpack format wants 2052 bytes. Read from the socket until you have received enough data first.
Upvotes: 2