Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to struct unpack c null terminated string?

Tags:

python

c

I used tcp to send a data to python server. The data is like:

struct protocol
{
    unsigned char prot;
    int id;
    char name[32];
}

Look at the name field, it is a null terminated string max size is 32. Now I use strcpy.

protocol p;
memset(&p, 0, sizeof(p));
strcpy(name, "abc");

Now I unpack it using python.

prot,id,name = struct.unpack("@Bi32s")

Now the len(name) is 32. But I need get the string of "abc" when the length is 3.

How can I do that?

like image 926
tjhack Avatar asked Sep 26 '14 12:09

tjhack


1 Answers

Simply get the substring up to the first \0:

prot,id,name = struct.unpack("@Bi32s")
name= name[:name.index("\0")]

This has the particularity that it will check and fail (throw ValueError) if no \0 appears inside the string.

like image 156
loopbackbee Avatar answered Sep 21 '22 14:09

loopbackbee