Packet parsing problem...

Erno Kuusela erno-news at erno.iki.fi
Mon Feb 26 19:46:26 EST 2001


In article <97ek6i$o6d at news.or.intel.com>, "Brian Geddes"
<brian.j.geddes at intel.com> writes:

| Here's my situation:
| There is an already-existing server (written in C++), which communicates
| with clients through 1-packet messages.  Each packet consists of a header of
| 2 or 3 C++ DWORDs, followed by 0 to n bytes of data.  I have to write a
| Python client to communicate with this server.

| In python, is there any structure that approximates the C++ DWORD?  I need
| to be able to parse incoming packets, as well as properly form messages to
| the server.

i don't know what a DWORD is, but i suspect it might be an alias
for some integer or pointer type in C++ on your software platform. in
that case you can use the struct module to convert a sequence
of bytes to the corresponding integer. things to keep
in mind when using the struct module for on the wire protocols:

1) padding. for example, on the machine i'm reading my news on,
>>> struct.calcsize('ich')
8
the struct module attempts to emulate the layout of c structs
in memory on your platform, and that often includes padding.
so it may be better to unpack the packets one item at a time.

2) portability - the sizes of the types use by the stuct module
can vary accross platforms. you may decide it's ok to not
be portable, or you may want to use different formats on different
platforms you want your program to run on, or for purists,
you may want to abandon the struct module completely for this
purpouse and do the work completely by hand via ord() an shifts.
also byte endianness - you probably need to specify the endianness
explicitly.

it would be nice to have a struct-ish module in the standard
distribution that would be geared towards working with data
formats with known bit layout...

  -- erno



More information about the Python-list mailing list